Prashant
Prashant

Reputation: 702

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)

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

}

Upvotes: 0

Views: 598

Answers (3)

Usman Saleem
Usman Saleem

Reputation: 1655

Rohit already explained it beautifully. Just to add my 2 cents, you should first check the subclass type and then typecast, for instance:

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?

Upvotes: 0

Tom
Tom

Reputation: 44871

You would need to move the method declaration to the abstract class.

Upvotes: 0

Rohit Jain
Rohit Jain

Reputation: 213311

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.

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.

Upvotes: 4

Related Questions