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?
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?
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.
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
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.