I have to work to a piece of code where there's this class with a bunch of static methods to be called from other classes.
I've created some new classes with an hierarchy like the following one:
public abstract class Superclass implements Comparable, Serializable
{
//Superclass stuff
}
public class MidClass extends Superclass implements Comparable, Serializable
{
//MidClass stuff
}
public class SubClass1 extends SuperClass implements Comparable, Serializable
{
//SubClass1 stuff
}
public class SubClass2 extends MidClass implements Comparable, Serializable
{
//SubClass2 stuff
}
Given that I need to call a different static method for every different subclass type, I've also added the following overloaded method to the first class:
public static objForMidClass elaborationMethod(MidClass midClass)
{
//Stuff to do with MidClass obj
}
public static objForSubClass1 elaborationMethod(SubClass1 subClass1)
{
//Stuff to do with SubClass1 obj
}
public static objForSubClass2 elaborationMethod(SubClass2 subClass2)
{
//Stuff to do with SubClass2 obj
}
In the class from where I call the static methods I've something like
//Inside "object" and "inputList" Lists there's the correct type/subtype
List<SuperClass> inputList = (List<SuperClass>) object;
if (inputList != null && inputList.size() > 0)
{
for(Iterator<SuperClass> it = inputList.iterator(); it.hasNext(); )
{
SuperClass item = it.next();
//Next line gives the error:
//"elaborationMethod(MidClass) in the type classWithStaticMethods is not applicable for the arguments (Superclass)"
AnotherClass retItem = classWithStaticMethods.elaborationMethod(item);
{
}
Could you tell me why it doesn't recognize that the objects passed are all instances of subclasses of SuperClass and, hence, that it must search for the static method of the corresponding SubClass type?
Also, what could be a correct alternative way to model this situation?