public class Parent {
int num = 10;
public void method(){
System.out.println("Parent method");
}
}
public class Child extends Parent {
int num = 20; // Why this declaration is allowed ?
public void method(){
System.out.println("Child method");
}
public static void main(String[] args) {
Parent f = new Child();
Child f2 = new Child();
System.out.println(f.num);
System.out.println(f2.num);
}
}
为什么子类中允许声明同名变量。 根据继承, child 应该继承 parent 的属性(property)。 请解释一下。
最佳答案
Why this declaration is allowed ?
因为该语言允许覆盖方法和隐藏成员 - 在您的情况下,您隐藏 parent num
成员。
子级的 num
值为 20
,如果您需要访问父级的 num
值,则必须执行以下操作:
int parentNum = super.num;
关于Java 继承 - 父级和子级的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31518166/