Aleksandar
Aleksandar

Reputation: 110

Is it possible to call a subclass specific method if only the superclass object has been initialized?

Lets deduct from a very simple example: Class a:

public class a{
public a{}

Subclass b inherits a:

public class b inherits a{
public b{super}
public void customMethodB(){}

Subclass c inherits a:

public class c inherits a{
public c{super}
public void customMethodC(){}

Main:

public class Main{
public static void main(String[] args){
a newObject = null;
//User can now choose through input if he wants to create b or c. Lets say he creates b:
newObject = new b();
//His choice is stored in a string.
String userChoice = b;
//I now call the general object from another method for the user to interact with.
//(I have a feeling it is here my problem is).
}

userInteraction(a newObject, String userChoice){
if (userChoice.equals("b"){
newObject.customMethodB();
}
else if (userChoice.equals("c"){
newObject.customMethodC();
}

}

Here lies my problem: I can not call customMethodB nor customMethodC even though the object is created as b in main. Is this due to the parameter type being a in the userInteraction method? Would it be possible to do something like this without creating a method to pass the specific subclass type?

Upvotes: 0

Views: 51

Answers (1)

Zouhour Ncib
Zouhour Ncib

Reputation: 51

Your method customMethodB does not exist in your type a. In order to call this method, you have to cast your object ( down cast is possible here )

if (userChoice.equals("b") && newObject instanceof b){
((b)newObject).customMethodB();
}

Upvotes: 1

Related Questions