0

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?

Mady Daby
  • 1,271
  • 6
  • 18
  • The Visitor Design Pattern might be the best way to solve this in an OOP-compliant way. Otherwise, you're resigned to using multiple collections, one for each sub-type, or using reflection or the instanceof operation, both of which give the code a bad non-oops smell. Please have a look at this related question and its answers: [Dynamic dispatch (runtime-polymorphism) with overloaded methods without using instanceof](https://stackoverflow.com/questions/47038187/dynamic-dispatch-runtime-polymorphism-with-overloaded-methods-without-using-in) – Hovercraft Full Of Eels Apr 22 '21 at 23:14

1 Answers1

-1

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.
}
Asis
  • 683
  • 3
  • 23