Home / Programs / Method Overriding in Java Example 3
🚀 Programming Example

Method Overriding in Java Example 3

👁 1,608 Views
💻 Practical Program
📘 Step Learning
Method Overriding in Java Example 3

💻 Program Code

 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
   }
}
                        

🖥 Program 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".

📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.