【发布时间】:2019-01-27 19:39:05
【问题描述】:
class Grand {
int x = 10;
}
class Parent extends Grand{
int x = 20;
}
class Childs extends Parent{
int x = 30;
void show(){
System.out.println(this.x);
System.out.println(super.x); //accessing parent's member
System.out.println((Grand)this.x); //why type-casting
}
我知道在 Java 中使用 super 关键字,我们可以访问被子方法/成员隐藏/覆盖的父方法/成员。
但是在多级继承中,我们使用类型转换子对象来访问父对象的父方法。
类型转换如何在内部工作以访问超级的父类成员。有没有其他方法可以做到这一点?
我们可以使用类型转换类似地访问这些方法吗?
【问题讨论】:
-
方法可以被覆盖,但是字段不能被覆盖。了解虚拟方法/覆盖。
标签: java inheritance casting