[英]How to call an non overide method of child class using parent object reference
Here is my code want to access child class method of AdapterVer1 getAdaptObj1() (without type casting) using object reference of AdapterVersion (Parent class) 这是我的代码想要使用AdapterVersion的对象引用(父类)访问AdapterVer1 getAdaptObj1()的子类方法(无类型转换)
abstract class AdapterVersion {
public abstract void getMObject();
public abstract void getCObject();
}
public class AdapterVer1 extends AdapterVersion {
@Override
public void getMObject() {
System.out.println("AdapterVer1 Mont");
}
@Override
public void getCObject() {
System.out.println("AdapterVer1 Conf");
}
public void getAdaptObj1() {
}
}
public class AdapterFactory {
public static void main(String []a){
AdapterFactory adapterFactory= new AdapterFactory();
AdapterVersion adpater = adapterFactory.getMyObject("ver1");
adpater.getAdaptObj1(); // Unable to do that
((AdapterVer1)adpater).getAdaptObj1(); // Working but DONT WANT THIS
}
public AdapterVersion getMyObject(String version){
if(version.equals("ver1")){
return new AdapterVer1();
}else{
return new AdapterVer2(); // another declared class
}
}
}
You can't do that. 你不能那样做。 Because at compile time, the compiler checks whether the method you invoked is accessible or visible in the class of the reference you are using or not.
因为在编译时,编译器会检查您调用的方法在您正在使用的引用的类中是否可访问或可见。
So, in this case, since the reference is of Parent
class, the compiler will look for the method declaration in the Parent class first in order to successfully compile the code. 因此,在这种情况下,由于引用是
Parent
类的,因此编译器将首先在Parent类中查找方法声明,以便成功编译代码。
Remember: - 请记住:-
Compiler is worried about the Reference type, and at runtime, the actual object type is considered, to decide which method to actually invoke. 编译器担心引用类型,并且在运行时会考虑实际的对象类型,以决定实际调用哪种方法。
The only option you have is to typecast, in which case, the compiler now looks into the class in which you typecasted the reference. 您唯一的选择就是进行类型转换,在这种情况下,编译器现在将查找您对类型进行引用转换的类。 Other option is, you can declare an abstract method with that name in Parent class, but from your question, it seems like you explicitly haven't done that.
另一个选择是,您可以在Parent类中声明具有该名称的抽象方法,但是从您的问题来看,您似乎似乎还没有这样做。
您将需要将方法声明移至抽象类。
Rohit already explained it beautifully. 罗希特(Rohit)已经对此进行了精美的解释。 Just to add my 2 cents, you should first check the subclass type and then typecast, for instance:
只需加上我的2美分,您就应该首先检查子类的类型,然后进行类型转换,例如:
if(adapter instanceof Adapterver1) {
((AdapterVer1)adpater).getAdaptObj1();
}
This way your code will be safer if it tries to handle a new subclass which doesn't declare such method. 这样,如果您的代码尝试处理未声明此方法的新子类,则代码将更安全。
But the question you must ask, if you already know what subclass method to call, why accessing it from superclass reference? 但是您必须问一个问题,如果您已经知道要调用的子类方法,为什么要从超类引用中访问它呢?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.