I want to have a base class and a couple of classes extending it.
Then I want to have an array that could be either of the two extending classes.
I was hoping to do something like this:
class Base{ }
class A extends Base {}
class B extends Base {}
then I want an array that could be either A or B so I use Base in array declaration
Base[] it = Base[2];
it[0] = new A();
it[1] = new B();
I’m not sure if I’m doing this correctly or if this allowed.
Thanks
You are missing the
newkeyword:Other then that – the approach is just fine. An array of type
Base[]can hold objects of typeAandB, since they are themselves extending the typeBase.Example:
Will result, as expected in printing: