如何调用Parent重写方法

Kic*_*ick 6 java polymorphism inheritance

我有两个类 Parent 和 Child。在 Child 类中,我调用父类重写方法(show)。在父类中,我调用另一个方法(display),但由于调用了 Child 方法,该方法也被重写。我想从show方法调用Parent方法display。

public class Parent {


    public void show()
    {
        System.out.println("Show of parent ");
        this.display();
    }

    public void display()
    {
        System.out.println("Display of parent");
    }

}

public class Child extends Parent{

    public void show()
    {
        System.out.println("Show of child ");
        super.show();
    }

    public void display()
    {
        System.out.println("Display of child");
    }

    public static void main(String[] args) {
        Parent obj = new Child();
        obj.show();
    }


}
Run Code Online (Sandbox Code Playgroud)

输出 :

Show of child 
Show of parent 
Display of child
Run Code Online (Sandbox Code Playgroud)

需要 :

Show of child 
Show of parent 
Display of parent
Run Code Online (Sandbox Code Playgroud)

即我想从同一个类的方法调用display()父类的方法show()

Roa*_*aim 6

当您重写子对象中的 display() 方法时,从子对象调用它将会调用被重写的方法而不是父对象的方法,因为它被重写了。如果你想执行一些操作,同时也调用父类的方法,那么你需要调用 super.display() 来执行父类的 display() 方法。所以,

  1. 如果您只想执行父级的 display() 方法,则不要在特定子级中覆盖它。

  2. 如果您只想执行子级的显示,那么现有代码就可以了。

  3. 如果您想调用父级的 display() 方法,并且还想执行一些其他任务,请将它们与 super.display() 方法混合。

例子

根据我的上述解释,我正在跟踪 3 个孩子,

Child1很可能是您在这里需要的,因为它将打印父级的 display() 方法,

public class Child1 extends Parent{

     // Simply deleting this method will produce exactly the same result
        public void display()
        {
            super.display();
        }

    }
Run Code Online (Sandbox Code Playgroud)

Child2中,我们忽略父级的 display() 方法,并且希望 child2 的对象仅执行 child2 的 display() 方法中编写的命令

public class Child2 extends Parent{

        public void display()
        {
            System.out.println("Display of child");
        }

    }
Run Code Online (Sandbox Code Playgroud)

Child3中,我们需要子级和父级的 display() 方法

public class Child3 extends Parent{

        public void display()
        {
             System.out.println("Display of child before parent's display");
             super.display();
             System.out.println("Display of child after parent's display");
        }

    }
Run Code Online (Sandbox Code Playgroud)

奖励:如果您不希望任何子级覆盖其 display() 方法,请在父级的 display() 方法之前添加最终修饰符。


Gho*_*ica 3

有什么问题:

public void show()
{
    System.out.println("Show of child ");
    super.show();
    super.display();
}
Run Code Online (Sandbox Code Playgroud)

郑重声明:您真的非常非常想在您认为覆盖某些内容的每个方法上添加@Override。经常发生这样的情况:您只是假设要覆盖某些内容,而没有实际执行它。@Override 指示编译器在您犯此类错误时告诉您。

编辑:请注意 - 似乎您希望在某些情况下将 show+display 称为“一起”。如果是这样:在您的“界面”上只放置一种方法,而不是两种!我的意思是:如果这些方法的想法是一个接一个地运行,那么提供一种有意义的方法来做到这一点。

换句话说:良好的界面可以轻松地做正确的事情;并且很难做错。在那里有两个方法,并期望其他代码按顺序调用它们会达到与该想法相反的效果。它很容易出错;更难把事情做好!

最后:命名已经指出当前存在一定的设计问题。例如:“展示”和“展示”之间到底有什么区别?!

  • 还是不知道你在说什么。由于调用两个超级方法的奇怪要求,“紧密”耦合开始发挥作用。当前的问题是“你的”设计;而不是多态或继承。 (2认同)