【问题标题】:Parent class reference pointing to Child class Object. Call only parent class method (JAVA) [duplicate]指向子类对象的父类引用。仅调用父类方法(JAVA)[重复]
【发布时间】:2016-04-05 18:30:41
【问题描述】:

我有父子关系类和一个覆盖方法,我只想显示父类方法。

class Parent{
    public void display(){
        System.out.println("Parent class display....");
    }
}
class Child extends Parent{
    public void display(){
        System.out.println("Child class display....");
    }
}

public class Demo {
    public static void main(String... args)  {
        Parent parent = new Child();
        parent.display();
    }
}

期望的输出:- 父类显示......

这可能吗?

【问题讨论】:

  • 最好在标签中添加你需要哪种程序语言才能工作......
  • 不能直接调用 Parent 方法,因为你指的是 Child 对象。但是,您可以通过调用 super.display() 打印“Parent class Display....”

标签: java inheritance


【解决方案1】:

直接,不。要访问超类实现,您必须以某种方式公开它,否则它在外部根本不可见。有几种方法可以做到这一点。

子方法调用超级

您可以向Child 添加一个调用Parentdisplay() 实现的方法:

public void superDisplay()
{
    super.display();
}

您必须提供您的参考才能拨打电话:

((Child)parent).superDisplay();

请注意,向Parent 添加一个调用display() 的方法不会有帮助,因为由于多态性,它会为Child 实例调用Child.display()

在扩展 swing 组件时,通常会使用与此技术类似的东西,其中子组件的 paintComponent() 实现经常调用 super.paintComponent()

反思

虽然通常是杂乱无章的设计表明糟糕的设计,但反射会为您提供您想要的东西。只需获取Parent 类的display 方法并在Child 实例上调用它:

try {
    Parent.class.getMethod("display").invoke(parent);
} catch(SecurityException | NoSuchMethodException | IllegalArgumentException | IllegalAccessException | InvocationTargetException | ex) {
    // oops!
}

【讨论】:

    【解决方案2】:

    如果您只是在寻找一种方法,您可以在两个类中将您的display() 方法声明为static

    public static void display(){
    }
    

    【讨论】:

    • 有 99% 的把握,这对 OP 没有帮助。
    • 谢谢我的解决方案。
    猜你喜欢
    • 1970-01-01
    • 2011-04-17
    • 1970-01-01
    • 2012-07-13
    • 1970-01-01
    • 1970-01-01
    • 2020-04-26
    • 2020-08-09
    相关资源
    最近更新 更多