简体   繁体   English

来自父 class ZD52387880E1EA22817A72D37592138 的 arraylist 中的子 Class 对象的方法调用

[英]Method Calls from Child Class objects in arraylist of parent class Java

So I have a parent class with a series of child classes for some objects I need to use in a program.所以我有一个父 class 和一系列子类,用于一些我需要在程序中使用的对象。

class parentClass{

}

class childClass1 extends parentClass {

}

class childclass2 extends parentClass {

}

The parent class has 2 variables with their getters and setters and a super Constructor.父 class 有 2 个变量及其 getter 和 setter 以及一个超级构造函数。 The child classes have unique methods, one has a further set of variables that need their own getters and setters and they all their own constructor so I can make objects (which is why I'm not using abstract classes).子类有独特的方法,一个有另外一组需要自己的 getter 和 setter 的变量,它们都是自己的构造函数,所以我可以创建对象(这就是我不使用抽象类的原因)。

I need a data structure I can use to hold objects of the different child class types and call the methods.我需要一个可以用来保存不同子 class 类型的对象并调用方法的数据结构。 I've tried to do it as an array list but I'm not sure how to declare it if I do it as, I've tried implementing and filling the array list like this:我试图将它作为一个数组列表来做,但如果我这样做,我不确定如何声明它,我已经尝试像这样实现和填充数组列表:

List<parentClass> listofthings = new ArrayList<parentClass>();

listofthings.add(new childclass1(1, "String1"));
listofthings.add(new childclass2(2, "String2", "uniqueString", 2.2, false)); ...etc.

Does not seem to work correctly, as I can only call the common methods inherited from the parent class.似乎不能正常工作,因为我只能调用从父 class 继承的常用方法。 Any suggestions?有什么建议么?

You can use instanceOf to check if the object is an instance of a particular class then force type the instance to its Class after that you can use its methods.您可以使用instanceOf检查 object 是否是特定 class 的实例,然后将实例强制键入其 Class 之后您可以使用其方法。

For example:例如:

parentClass obj = listofthings[0];
if( obj instanceof childClass1){
   childClass1 class1 = (childClass1) obj;
   // now class1 objc will have the childClass1 methods.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM