Method Overriding in Java Example 3

Java Programming Language / Class, Object and Methods in java

1524

Program:

 class Parent {
   public void display() {
      System.out.println("i am parent");
   }
}

class Child extends Parent {
   public void display() {
      System.out.println("i am child class");
   }
}

public class MethodOverriding {

   public static void main(String args[]) {
      Parent a = new Parent();   // Parent reference and object
      Parent b = new Child();   // Parent reference but Child object

      a.display();   // runs the method in Parent class
      b.display();   // runs the method in Child class
   }
}

Output:

i am parent
i am child class
Press any key to continue . . .

Explanation:

The above Java code demonstrates the concept of Method Overriding.

The code defines a class Parent with a method named display() that prints "i am parent" to the console. The class Child extends Parent and overrides the display() method to print "i am child class".

In the main() method of the MethodOverriding class, two objects are created. The first object a is of type Parent and calls the display() method of the Parent class, which prints "i am parent".

The second object b is of type Parent but refers to the object of the Child class. When the display() method is called using the object b, it invokes the display() method of the Child class because of the dynamic method dispatch mechanism in Java. Thus, the output is "i am child class".


This Particular section is dedicated to Programs only. If you want learn more about Java Programming Language. Then you can visit below links to get more depth on this subject.