[英]why can't i call a subclass method from a superclass object
Consider below two classes
class Parent {
public void parentMethod(){
System.out.println("inside parentMethod");
}
}
public class child extends Parent {
public void childMethod(){
System.out.println("inside childMethod");
}
public static void main(String [] args){
Parent p =new Child();
p.childMethod();
}
}
Why cannot i call the child class method with following syntax?为什么我不能使用以下语法调用子类方法? Parent p =new Child();
父 p = 新子 (); p.childMethod();
p.childMethod();
The type of object that p holds is that of Child but still i cannot call child class method. p 持有的对象类型是 Child 的类型,但我仍然无法调用子类方法。 Why such a call cannot complete in java?
为什么这样的调用在java中无法完成?
Because the variable is of type Parent
.因为变量的类型是
Parent
。 Which means it can hold any object of type Parent
, be it a Child
or anything else that implements the Parent
class.这意味着它可以保存任何
Parent
类型的对象,无论是Child
还是其他任何实现Parent
类的对象。 The compiler can't guarantee that the variable will hold a Child
, because you told it to make the variable a Parent
.编译器不能保证该变量将包含一个
Child
,因为您告诉它使该变量成为一个Parent
。
To invoke a method on Child
, make the variable that type:要调用
Child
上的方法,请将变量设为:
Child p = new Child();
p.childMethod();
Alternatively, if you can yourself guarantee that the variable is pointing to a Child
object, you can cast it:或者,如果您可以自己保证变量指向
Child
对象,则可以强制转换它:
Parent p = new Child();
Child c = (Child)p;
c.childMethod();
Though there's an argument to be made that if you can always guarantee that the variable will be a Child
then it should have been of type Child
in the first place.尽管有一个论点是,如果您始终可以保证变量将是
Child
那么它首先应该是Child
类型。
You cannot call that method because Parent#childMethod
is not a method.您不能调用该方法,因为
Parent#childMethod
不是方法。 Child#childMethod
is a method. Child#childMethod
是一种方法。
Think about this:想一想:
Parent p = new Parent();
p.childMethod();
Should you be able to do this?你应该能够做到这一点吗? No, because you have an instance of
Parent
.不,因为您有一个
Parent
实例。
Your l-value is Parent
so you will only be able to call methods that are defined in Parent
.您的左值是
Parent
因此您将只能调用Parent
中定义的方法。 To do what you want, you'd need to cast Parent
to a Child
, but you need to make sure that it actually is an instance of Child
:要执行您想要的操作,您需要将
Parent
转换为Child
,但您需要确保它实际上是Child
一个实例:
if(p instanceof Child) {
((Child)p).childMethod()
}
This is because the reference variable type is of type Parent.这是因为引用变量类型是 Parent 类型。 Therefore, the variable only has access to the attributes and behaviors of the reference class.
因此,变量只能访问引用类的属性和行为。 Note, you can override methods in the child class... For example:
请注意,您可以覆盖子类中的方法...例如:
public class child extends Parent {
@Override
public void parentMethod(){
System.out.println("inside childMethod");
}
public static void main(String [] args){
Parent p =new Child();
p.childMethod(); // PRINTS "inside childMethod"
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.