Hiding Fields in Java Inheritance(Java继承中的隐藏字段)
本文介绍了Java继承中的隐藏字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在类中,与超类中的字段同名的字段会隐藏超类的字段.
Within a class, a field that has the same name as a field in the superclass hides the superclass's field.
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;
}
}
谁能帮我解释一下结果?
Can someone explain the results for me?
推荐答案
在java中,字段不是多态的.
In java, fields are not polymorphic.
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继承中的隐藏字段
基础教程推荐
猜你喜欢
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01