【发布时间】:2021-01-11 00:52:34
【问题描述】:
我正在使用 java 解决简单的 OOP 概念练习问题 该问题给出了一个uml图并要求实施。 我遇到了一个问题,它要求我从子类访问祖父母类中的方法。
见插图:
class Grandparent {
public void Print() {
System.out.println("Grandparent's Print()");
}
}
class Parent extends Grandparent {
public void Print() {
System.out.println("Parent's Print()");
}
}
class Child extends Parent {
public void Print() {
super.super.Print(); // Trying to access Grandparent's Print()
System.out.println("Child's Print()");
}
}
public class Main {
public static void main(String[] args) {
Child c = new Child();
c.Print();
}
}
我在所有地方都做了我的研究,我发现 java 不允许这样做,因为应用了 Encpculation 但是它在 C++ 中是允许的,我的问题是我可以做些什么来从不允许的祖父类( super. java 中的 super.method() ) 语句。
我的意思是我可以改变结构,保持原有的继承,并且可以在缺少 UML 的情况下访问该方法。
【问题讨论】:
标签: java oop inheritance encapsulation