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

Java 如何使用父类引用访问子类方法?,java,inheritance,downcast,upcasting,Java,Inheritance,Downcast,Upcasting,使用父类引用变量访问子类方法时出错。 请帮帮我 我如何访问该方法 类父类 { 公开展览( { System.out.println(“在父类中显示方法”); } } 类子级扩展父级 { 公开作废印刷品() { System.out.println(“子类中的打印方法”); } } 公众阶级的悲观情绪 { 公共静态void main(字符串参数[]) { 父p1=新的子(); p1.print();//此处显示错误 } } 您可以进行演员阵容: class Parent { public

使用父类引用变量访问子类方法时出错。 请帮帮我

我如何访问该方法

类父类
{
公开展览(
{
System.out.println(“在父类中显示方法”);
}
}
类子级扩展父级
{
公开作废印刷品()
{
System.out.println(“子类中的打印方法”);
}
}
公众阶级的悲观情绪
{
公共静态void main(字符串参数[])
{
父p1=新的子();
p1.print();//此处显示错误
}
}
您可以进行演员阵容:

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
    }
}

您的
父类
类对您的
子类
中的方法一无所知。这就是为什么你会犯错误

一种可能的解决方案是将父类设置为抽象类,并在其中添加抽象方法,但在这种情况下,所有子类都应覆盖此方法:

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();
    }

}

该错误是由于父类对子类一无所知而导致的。修复错误的一种方法是执行显式转换
((子)p1).print()

编译器将
p1
视为
父级
,它没有
print()
,实际的运行时类型
子级
不重要。您还应该包括您收到的错误消息。