有 Java 编程相关的问题?

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

java如何从子类使用superparent类方法

abstract class SuperParent
{
    public abstract void Show();
    public void Display()
    {
        System.out.println("HI............I m ur grandpa and in Display()");
    }
}

abstract class Parent extends SuperParent
{
    public abstract void Detail(); 
    public void  Show()
    { 
        System.out.println("implemented  abstract Show()method of Superparent in parent thru super");
    }
    public void Display()
    {
        System.out.println("Override display() method of Superparent in parent thru super");    
    }
}

public class Child extends Parent
{
    Child()
    {
        super.Show();
        super.Display();
    }
    public void  Show()
    {
        System.out.println("Override show() method of parent in Child");
    }
    public  void Detail()
    {
        System.out.println("implemented abstract Detail()method of parent ");
    }
    public void Display()
    {
        System.out.println("Override display() method of Superparent and Parent in child ");    
    }

    public static void main(String[] args) {
        Child c1= new Child();
        c1.Show();
        c1.Display();

        Parent p1=new Child();
        p1.Detail();
        p1.Display();
        p1.Show();

    }
}

我用一个抽象方法show()和一个具体方法Display()创建了一个抽象类superparent。现在我们用一个抽象方法detail()和具体方法display()创建一个父类extends superparent,该方法由superparent重写,并实现show()方法,该方法在superparent中是抽象的,现在我创建一个子类extends Parent,使用父级中抽象的实现方法Detail()和父级中的overide display()方法以及父级中的superparent和overide show()。现在我创建了一个child实例并运行all方法,它调用all-child方法,很好。若我们想运行父方法,那个么我们就使用super。构造函数中的父方法,运行正常。但我如何从子类运行superparent方法display()


共 (1) 个答案

  1. # 1 楼答案

    Java语言不支持这一点

    您必须从Parent调用SuperParent.show(),并从Child调用此代码:

    abstract class Parent extends SuperParent {
    
        ...
    
        public void superParentShow() {
            super.Show();
        }
    }
    

    然后打电话

    super.superParentShow()
    

    Child

    相关问题: