[英]How to access child class method using parent class refrence?
我在使用父类引用变量访问子类方法时出错。 请帮我。
我如何访问该方法?
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
}
}
您的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();
}
}
该错误是由于Parent
类对Child
类一无所知引起的。 修复错误的一种方法是执行显式强制转换((Child) 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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.