0

I have gone through many links about reference object in java. Still I don't have clear idea.

superclass obj = new subclass();

How will obj get instantiated? What is the use of it?

Vikram
  • 3,996
  • 8
  • 37
  • 58
user1526671
  • 817
  • 4
  • 16
  • 33
  • 1
    Please post at least one link out of many that you have gone through, that didn't make you understand this. – Rohit Jain Nov 15 '12 at 18:23

4 Answers4

2

obj is a reference variable whose type is superclass. That means that such a variable can point to an object of type superclass or any of its subclasses. In your case you are instantiating one such subclass, called subclass in your example. Now you can call any method on this object that is declared in superclass—and which the subclass is guaranteed to possess either by inheriting or by overriding.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
0

No, obj won't be instantiated (it is reference of type superclass). Subclass() will be instantiated and obj points to subclass instance.

I would suggest reading this tutorial to understand more about what does that mean object and reference.

kosa
  • 65,990
  • 13
  • 130
  • 167
0

reference and object are two different things, reference may refer to one of the object (or it can be null, referring no where)

how object gets initialized ?

there are lots of ways but in this example using new key word

what is the use of it.

see polymorphism

jmj
  • 237,923
  • 42
  • 401
  • 438
0

Here the SuperClass will hold the reference of the SubClass and the methods which are overridden by SubClass will be executed of the SubClass otherwise all the methods of the SuperClass will be executed.

Bhavik Ambani
  • 6,557
  • 14
  • 55
  • 86