Is there a way in Java to call different child method depending on which subclass is the object?

orlin614 :

In my project I have a superclass and two subclasses extending from it. There is a method in the superclass that is overriden differently in each subclass. I want to know if it's possible to introduce a method (in another class) that takes object of either subclass as a parameter and calls a method overriden in one of subclasses (depending on to which subclass does the object belong).

public class Superclass{
    public int method(){return 0;}
}
public class Subclass1 extends Superclass{
    public int method(){return 1;}
}
public class Subclass2 extends Superclass{
    public int method(){return 2;}
}
public class CallingClass{
    public static int dependantCall(Superclass parameter){return parameter.method}

I want to be able to do something like

Subclass1 subclassObject = new Subclass1;
System.out.println(CallingClass.dependantCall(subclassObject));

and get output

1
Prashant Pandey :

Yes, it is entirely possible. Here's how that method would look like:

public <T extends Superclass> void foo(T subclassObject) {
...
} 

Or:

public void foo(Superclass obj) {
...
}

Note that in the above method, you can pass subclasses' objects as well (they are covariant data types).

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=309525&siteId=1