java—将通过继承创建的对象添加到链表并实现它们的方法

qv7cva1a  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(265)

我试图在链表中存储不同“类型”的对象。我有几个独特的“类型”类继承自 ProtoType (此处仅显示一种,共有5种类型)。
当我创建一个新对象时,我可以使用“type1.somemethods”访问其中的所有方法。我不知道的是,如何遍历列表,并根据它们在列表中的位置获得每个不同“类型”的方法。我想我可以使用“typelist.get(int index.somemethods()”。我只能使用与linkedlist关联的方法。
父类

public class ProtoType {

private int ID;
private int x;
private String type;
private int randomNumber;

public ProtoType(int ID, int x, String type ) {

   this.ID = ID;
   this.x = x;
   this.type = type;
   this.randomNumber = randomNumber;
}

 public int getID() {
    return ID;
}

public  int getX() {
   return x;
}

public void randomNumberGenerator(int max, int min) {
   Random r = new Random();
   randomNumber = r.nextInt(max - min + 1) + 1;

}
public int getRandomNum() {
   return randomNumber;
}
}

儿童班

public class Type1 extends ProtoType {

public Type1(int ID, int x, String type) {
    super(ID, x, type);

}
public void preformAction(){
    System.out.println(getRandomNum());
    switch (getRandomNum()){

    case 1:
    case 2:
        //Some action
        break;
    case 3: 
        //some action
        break;
    case 4:
        //some action
        break;
        }
    }
}

主要类别

import java.util.LinkedList;

public class TestMAin {

public static   void main(String[] args) {

   LinkedList typeList = new LinkedList();

   Type1 t1 = new Type1(1, 12, "type1");
      typeList.add(0, t1);
   Type1 t2 = new Type1(2, 13, "type1");
      typeList.add(1, t2);

   }
//////////////
// the issue
//iterate thru the array get the type 
//implement the methods of that type
/////////////

}
bz4sfanl

bz4sfanl1#

我有两个建议取决于一件事。继承的类是否使用方法重写?
例子:

public class ParentClass {
    public void method() {}
}

public class ChildA extends ParentClass {
    @Override
    public void method() {}
}

public class ChildB extends ParentClass {
    @Override
    public void method() {}
}

public class Main {
    public static void main(String[] args) {
        ArrayList<ParentClass> list = new ArrayList<>();
        list.add(new ChildA());
        list.add(new ChildB());

        for (int i = 0; i < list.size(); i++) {
            list.get(i).method(); //Will class the appropriate sub-classes implementation of method().
        }
    }
}

如果您不希望使用重写的方法,那么instanceof操作符可能就是您要查找的对象。

public class Main {
    public static void main(String[] args) {
        ArrayList<ParentClass> list = new ArrayList<>();
        list.add(new ChildA());
        list.add(new ChildB());

        for (int i = 0; i < list.size(); i++) {
            ParentClass obj = list.get(i);

            if (obj instanceof ChildA) {
                obj.childAMethod();
            }
            else if (obj instanceof ChildB) {
                obj.childBMethod();
            }
        }
    }
}

如果你发现自己依赖于instanceof操作符,你可能需要看看你的程序结构,因为它不被认为是面向对象设计的最佳选择。

相关问题