如何使用父类引用访问子类方法?

时间:2020-01-09 10:25:27

标签: java inheritance downcast upcasting

使用父类参考变量访问子类方法时出现错误。 请帮我。

如何访问该方法?

class Parent 
{
    public void show()
    {
        System.out.println("Show method in Parent class");
    }
}
class Child extends Parent
{
    public void print()
    {
        System.out.println("Print method in Child class");
    }
}
public class Downcast
{
    public static void main(String args[])
    {
        Parent p1=new Child();
        p1.print();//showing error here
    }
}

3 个答案:

答案 0 :(得分:1)

您的Parent类对Child类中的方法一无所知。这就是为什么您会出错。

一种可能的解决方案是使您的Parent类成为抽象类,并在其中添加抽象print()方法,但是在这种情况下,所有子类都应覆盖此方法:

abstract class Parent {

    public void show() {
        System.out.println("Show method in Parent class");
    }

    public abstract void print();
}

class Child extends Parent {

    @Override
    public void print() {
        System.out.println("Print method in Child class");
    }

}

public class Downcast {

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

}

答案 1 :(得分:0)

由于 appBar: AppBar( automaticallyImplyLeading: false, title: Text("Breeds of Dogs"), actions: <Widget>[ Icon(Icons.add_a_photo), ], ) 类对Parent类一无所知,因此导致了错误。解决错误的一种方法是执行显式强制转换Child

答案 2 :(得分:-1)

您可以进行投射:

class Parent 
{
    public void show()
    {
        System.out.println("Show method in Parent class");
    }
}
class Child extends Parent
{
    public void print()
    {
        System.out.println("Print method in Child class");
    }
}
public class Downcast
{
    public static void main(String args[])
    {
        Parent p1=new Child();
        ((Child) p1).print();// Out : Print method in Child class
    }
}
相关问题