[英]Sub class variable is not hiding the variable in super class
我刚刚了解到,如果有两个变量,一个在超类中,一个在子类中,它们具有相同的名称,则分配给子类中变量的值将隐藏超类中的变量值。 我已经编写了一个程序来检查该问题,但是该结果清楚地表明没有任何隐藏过程正在发生或是否真的在发生? 如果子类在超类中隐藏了变量,则“ Aa”和“ Ba”的值应为25,对吗? 请帮帮我。
注意:我是这个Java编程的新手。 请详细解释您的答案。 谢谢
这是代码
public class Super {
int a;
Super(int x) {
a = x;
}
}
class something extends Super {
int a;
something(int x, int y) {
super(x);
a = y;
}
}
class mainclass {
public static void main(String args[]) {
Super A = new Super(10);
something B = new something(10, 25);
System.out.println("The value of a in super class is" + A.a);
System.out.println("The value of a in sub class is" + B.a);
}
}
输出在这里:
The value of a in super class is10
The value of a in sub class is25
Aa
不应返回25,因为A
的类型是超类型Super
,并且没有隐藏。 这就是Aa
返回10的原因。
仅在Ba
中隐藏a
(因为B是扩展Super
并隐藏成员a
something
类型),因此它返回25。
是的,子类中的“ a”在超类中隐藏了“ a”。 这就是为什么要在某些构造函数的子类中分配“ a”的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.