What is the difference between
A a1 = new A();
A a2 = new B();
where B extends A
and also what happens if i do the following
a1 = new B();
Thanks.
What is the difference between
A a1 = new A();
A a2 = new B();
where B extends A
and also what happens if i do the following
a1 = new B();
Thanks.
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();
You can alter using objects of class A or B into objects a1 or b1. the matter is when you try to use a new method from class B than not exist in class A.
Class A Class B
.move() ( .move() ) inheritance
.walk() ( .walk() ) inheritance
.run() ( .run() ) inheritance
.jump()
.dance()
if you have an object like a1= new B() or a1=new A();
it works good for them both:
a1.move()
a1.run()
but this works just a1= new B()
a1.jump()
Firstly I'd recommend you to read on OOP inheritance and interfaces.
Now on to the question. A a1 = new A();
calls the constructor defined for A
, generating a new object of type A
with it's own reference in memory.
A a2 = new B();
will create a new object a2
of type B
with a new reference, just like a1
however, since you're defining a2
as of type A
and B
extends A
, a2
will only have access to methods defined in A
without having to do an explicit cast.
a1 = new B();
will simply overwrite a1 with a new object.
Let's assume a1 is stored in memory as current_a1 at a random address, this when you create it with a1 = new A();
, when the program reaches a1 = new B();
current_a1 will be set to the address of new B()
and the old_a1 will eventually be garbage collected if nothing else points towards it.
Example:
A a1 = new A(); a1 -> address_1
a1 = new B(); a1 -> address_2
address_1 is freed from memory if it isn't being pointed to/"used" anywhere else
I hope this helps! And next time before asking do a deeper search about the subject.