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.

其他提示

Compilation is fine as compiler sees we are defining a reference to its type. But at runtime JVM sees that it is pre-declared to store child types and when trying to store the parent type, the reverse definiton (child reference = parent obj) is not possible, so throws an exception.

It can be better understood by the following example-

class X {
    public void xMetod() {
        System.out.println("Called xMetod!");
    }
}

class Y extends X {
    public void yMethod() {
        System.out.println("Called yMethod!");
    }
}

public class InheritanceWithArrays {

    public static void main(String[] args) {
        X[] vetx= new Y[3];     // if new X[3] - then outputs in Called xMetod!
        vetx [0] = new X();     // Runtime exception-  java.lang.ArrayStoreException: X
        vetx[0].xMetod();   
    }

}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top