To take the first line A a1 = new A();
, A a1
is the reference to an object of type A, and A()
is a call to the constructor that creates a new instance of A.
If class B subclasses A, then you can write a1 = new B();
, since a1 is a reference to an object of type A, and the new B will have all the methods required to fullfil the “contract” of being an A. However, you won’t be able to directly call anything specific to B, since the reference is of type A.
BTW, the above is a super-brief rundown of this topic, and I’d recommend going through some kind of tutorial.
EDIT: Here’s an analogy/example: (FerrariWithSunRoof
extends Ferrari
)
Ferrari A = new Ferrari();
Ferrari B = new FerrariWithSunRoof();
You couldn’t call, say, B.openSunroof()
, since B is referenced as Ferrari
and thus the reference doesn’t have a concept of a sunroof (even though the actual instance has a sunroof). In order to do that, you’d have to reference it as a FerrariWithSunRoof
, i.e.:
FerrariWithSunRoof B = new FerrariWithSunRoof();
2
solved creating objects from different classes with same reference [duplicate]