Explanation
This Java program demonstrates two fundamental object-oriented programming concepts: Method Overriding and Dynamic Method Dispatch (also known as Runtime Polymorphism).
-
Base Class
shape: We start by defining a class namedshape. This class has a simple method calleddraw(), which, when invoked, prints "Drawing a shape" to the console. This acts as our generic blueprint for any shape. -
Derived Classes
circleandrectangle:- The
circleclassextends shape. This meanscircleis a specialized type ofshapeand inherits all its properties and methods. - Crucially,
circlealso has its owndraw()method. Notice the@Overrideannotation. This indicates that thedraw()method incircleis intentionally replacing (overriding) thedraw()method inherited from its parent classshape. Whencircle'sdraw()is called, it prints "Drawing a circle". - Similarly, the
rectangleclass alsoextends shapeandoverridesthedraw()method to print "Drawing a rectangle".
- The
-
MainClass and Dynamic Method Dispatch:- Inside the
mainmethod, we declare a reference variablesof typeshape:shape s;. This variable can point to any object that is ashapeor a subclass ofshape. - First Assignment:
s = new circle();. Here, we make theshapereferencespoint to a newcircleobject. Even thoughsis declared as ashape, it is currently holding an object of typecircle. - First Method Call:
s.draw();. When this line is executed, Java needs to decide whichdraw()method to call. Sincescurrently refers to acircleobject, Java's Dynamic Method Dispatch mechanism kicks in. It determines at runtime that the actual object type iscircle, and therefore, it calls thedraw()method defined in thecircleclass. The output will be "Drawing a circle". - Second Assignment:
s = new rectangle();. Now, the sameshapereferencesis made to point to a newrectangleobject. Thecircleobject previously referenced bysis now unreferenced (and subject to garbage collection if no other references exist). - Second Method Call:
s.draw();. Again, Dynamic Method Dispatch takes place. This time,srefers to arectangleobject, so Java calls thedraw()method from therectangleclass. The output will be "Drawing a rectangle".
- Inside the
In essence, the program shows how a single reference variable of a parent class type can be used to invoke different implementations of an overridden method based on the actual object it refers to at runtime.