基于子类类型调用不同的方法

时间:2017-03-10 09:59:37

标签: java polymorphism overloading

我必须使用一段代码来处理这个类,其中有一些静态方法可以从其他类调用。

我创建了一些具有以下层次结构的新类:

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
}

鉴于我需要为每个不同的子类类型调用不同的静态方法,我还将以下重载方法添加到第一个类:

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
}

在我称之为静态方法的课程中我会像

那样
//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);

    {
}

你能否告诉我为什么它没有认识到传递的对象都是SuperClass子类的所有实例,因此它必须搜索相应SubClass类型的静态方法?

另外,对这种情况进行建模可能是一种正确的替代方法吗?

1 个答案:

答案 0 :(得分:0)

您应该从overloading方法切换到overriding方法,并将static elaborationMethod方法移到各自的类中。

此时,您可以通过以下方式为每个elaborationMethod致电item

item.elaborationMethod();

只是为了让你明白我写了这个小例子。考虑与printName等效的elaborationMethod方法。

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class Polymorphism {

  public static void main(String[] args)
  {
    List<SuperClass> inputList = new ArrayList<>();

    inputList.add(new SuperClass() {});
    inputList.add(new MidClass());
    inputList.add(new SubClass1());
    inputList.add(new SubClass2());

    for (SuperClass s : inputList) {
      s.printName();
    }

  }

}


abstract class SuperClass {

  public void printName()
  {
    System.out.println("SuperClass");
  }
}


class MidClass extends SuperClass {

  public void printName()
  {
    System.out.println("MidClass");
  }
}


class SubClass1 extends SuperClass {

  public void printName()
  {
    System.out.println("SubClass1");
  }
}


class SubClass2 extends MidClass {
  // Missing printName
}