I have a test tomorrow and I have a doubt about inheritance in java.
Question: Suppose a program in java where Y is a subclass of X. Suppose that the following code is valid in the program:
Y[] vetY = new Y[3];
X[] vetX = vety;
Is the following assignment valid or not in this program? Justify.
vetX[0] = new X();
My answer(not sure): It is not valid because vetX
has the methods of Y
and I don't know what was implemented in Y. So it can compile but it will not run.
Your assumption is correct.
Array created via new Y[3]
can hold only objects of type Y
or its subclasses. It can't store instances of superclasses like X
because there is risk that X
will not have all methods available in Y
, so even if
vetx [0] = new X();
compiles fine (vetx is type of X[]
so compiler doesn't see anything wrong here), later you could try to access this object via vetY
(which is type of Y[]
) and try to invoke
vety[0].getPropertyAddedInY();
which instance of X
will not have.
So to prevent such situation at runtime each array checks what type of data someone is trying to put in it and in case it is unsupported type will throw java.lang.ArrayStoreException
.