Explanation
This Java code demonstrates two fundamental object-oriented programming concepts: Method Overriding and Dynamic Method Dispatch (also known as Runtime Polymorphism).
- Parent Class: We start with a base class named
Parent. It has a single method,print(), which simply prints "Parent class" to the console. - Subclass1:
subclass1extendsParent. This meanssubclass1inherits all members (methods and fields) ofParent. However,subclass1also provides its own version of theprint()method. This is Method Overriding – a subclass provides a specific implementation for a method that is already defined in its superclass. Whensubclass1'sprint()method is called, it will print "Subclass1". - Subclass2: Similar to
subclass1,subclass2also extendsParentand overrides theprint()method. Itsprint()method prints "Subclass2". - Main Class: The
Mainclass contains themainmethod, which is the entry point of the program.- Inside
main, a variableaof typeParentis declared (Parent a;). This variable is a reference type that can point to objects of typeParentor any of its subclasses. a = new subclass1();: Here, an object ofsubclass1is created, and the referenceais made to point to thissubclass1object. This is a form of polymorphic assignment, where a superclass reference points to a subclass object.a.print();: Whenprint()is called using theareference, the Java Virtual Machine (JVM) determines whichprint()method to execute at runtime. Sinceais currently pointing to asubclass1object, theprint()method fromsubclass1is invoked, printing "Subclass1". This decision made at runtime is Dynamic Method Dispatch.a = new subclass2();: The referenceais now reassigned to point to a newly createdsubclass2object.a.print();: Again,print()is called. Becauseanow points to asubclass2object, the JVM dynamically dispatches the call to theprint()method ofsubclass2, printing "Subclass2".
- Inside
In essence, the code demonstrates how a single reference variable (a of type Parent) can be used to invoke different implementations of the same method (print()) based on the actual type of the object it refers to at any given moment during program execution.