gpt4 book ai didi

java - 在java中访问祖 parent 方法

转载 作者:行者123 更新时间:2023-12-04 01:13:37 25 4
gpt4 key购买 nike

我正在使用 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 的情况下访问该方法。

最佳答案

  1. 无法在 java 中调用 super.super.foo()。

  2. 您可以通过以下方式隐式执行此操作:

    public class Grandparent {
    public void Print() {
    System.out.println("Grandparent's Print()");
    }
    }
    class Parent extends Grandparent {
    public void Print() {
    super.Print(); // Here we can add a call to Print() from Grandparent.
    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();
    }
    }
  • 注意:尽量使用方法的命名约定。 Print() -> print()
  • 使用 lowerCamelCase

关于java - 在java中访问祖 parent 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64051362/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com