使用父类参考变量访问子类方法时出现错误。 请帮我。
如何访问该方法?
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
}
}
答案 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
}
}