gpt4 book ai didi

java - 在 Java 继承中隐藏字段

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:55:05 25 4
gpt4 key购买 nike

在类中,与父类(super class)中的字段同名的字段隐藏父类(super class)的字段。

public class Test {

public static void main(String[] args) {

Father father = new Son();
System.out.println(father.i); //why 1?
System.out.println(father.getI()); //2
System.out.println(father.j); //why 10?
System.out.println(father.getJ()); //why 10?

System.out.println();

Son son = new Son();
System.out.println(son.i); //2
System.out.println(son.getI()); //2
System.out.println(son.j); //20
System.out.println(son.getJ()); //why 10?
}
}

class Son extends Father {

int i = 2;
int j = 20;

@Override
public int getI() {
return i;
}
}

class Father {

int i = 1;
int j = 10;

public int getI() {
return i;
}

public int getJ() {
return j;
}
}

有人可以为我解释一下结果吗?

最佳答案

在 java 中,字段不是多态的。

Father father = new Son();
System.out.println(father.i); //why 1? Ans : reference is of type father, so 1 (fields are not polymorphic)
System.out.println(father.getI()); //2 : overridden method called
System.out.println(father.j); //why 10? Ans : reference is of type father, so 2
System.out.println(father.getJ()); //why 10? there is not overridden getJ() method in Son class, so father.getJ() is called

System.out.println();

// same explaination as above for following
Son son = new Son();
System.out.println(son.i); //2
System.out.println(son.getI()); //2
System.out.println(son.j); //20
System.out.println(son.getJ()); //why 10?

关于java - 在 Java 继承中隐藏字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12244670/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com