有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何调用父重写方法

我有两个班,父母和孩子。我从子类调用父重写方法(show)。在父类中,我调用了另一个方法(display),但由于调用了哪个子方法,该方法也被重写。 我想从show方法调用父方法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();
    }


}

输出:

Show of child 
Show of parent 
Display of child

需要:

Show of child 
Show of parent 
Display of parent

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


共 (1) 个答案

  1. # 1 楼答案

    public class Parent {
    
    
        public void show()
        {
            System.out.println("Show of parent ");
            display();
        }
    
        public static 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 static void display()
        {
            System.out.println("Display of child");
        }
    
        public static void main(String[] args) 
        {
            Parent obj = new Child();
            obj.show();
        }
    
    }
    

    解释:

    这与隐藏方法有关。隐藏方法的规则与添加static关键字覆盖的规则相同。使用static关键字,可以隐藏display()方法。 所以当obj调用方法show()时,计算机会这样运行: 我有对象ChildParent引用(它可以是Child引用,在本例中输出仍然相同)。 Child对象有show()打印“子对象的显示”,然后调用Parent类的show()方法。 Parent{}方法打印“显示父对象”,然后调用{}。由于display()staticParent只知道自己的display()方法,因此打印“父项显示”

    虽然,这是一个选项,但最好不要使用它,因为它可能会导致混乱和难以阅读的代码