Search code examples
javasubclasssuperclassobjectinstantiation

Reference object in java


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?


Solution

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