使用super访问Java中祖父母的成员

在Java中直接访问祖父母的成员:

null

预测以下Java程序的输出。

JAVA

// filename Main.java
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()
{
// Trying to access Grandparent's Print()
super . super .Print();
System.out.println( "Child's Print()" );
}
}
public class Main {
public static void main(String[] args)
{
Child c = new Child();
c.Print();
}
}


输出:

prog.java:20: error: <identifier> expected        super.super.Print();              ^prog.java:20: error: not a statement        super.super.Print(); 

行“super.super.print();”处出错。在Java中,类不能直接访问祖父母的成员。不过,C++中允许使用。在C++中,我们可以使用范围解析运算符(::)访问继承层次结构中的任何祖先成员。 在Java中,我们只能通过父类访问祖父母的成员。

例如,以下程序编译并运行良好。

JAVA

// filename Main.java
class Grandparent {
public void Print()
{
System.out.println( "Grandparent's Print()" );
}
}
class Parent extends Grandparent {
public void Print()
{
super .Print();
System.out.println( "Parent's Print()" );
}
}
class Child extends Parent {
public void Print()
{
super .Print();
System.out.println( "Child's Print()" );
}
}
public class Main {
public static void main(String[] args)
{
Child c = new Child();
c.Print();
}
}


输出

Grandparent's Print()Parent's Print()Child's Print()

为什么java不允许访问祖父母的方法?

它违反了封装。你不应该绕过父类的行为。有时可以绕过自己类的行为(尤其是在同一个方法中),但不能绕过父类的行为,这是有道理的。

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞10 分享