简体   繁体   中英

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 parentClass{

}

class childClass1 extends parentClass {

}

class childclass2 extends parentClass {

}

The parent class has 2 variables with their getters and setters and a super Constructor. 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).

I need a data structure I can use to hold objects of the different child class types and call the methods. 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. 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.

For example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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