A method defined in a super class is inherited by its subclass and is used by the objects, created by the subclass. Inheritance allows us to define and use methods repeatedly in subclasses, without having to define the methods again in subclass. But if we want an object to respond to the same method, but have different behavior when that method is called; for this, we should override the method defined in the super class. This is done by defining a method in the subclass that has the same name, same arguments and same return type as a method in the super class. Then, when that method is called, the method defined in the subclass is invoked and executed instead of the one defined in the superclass. This is called Method Overriding. class base { // disp() is a method of class base void disp() { System.out.println("Base class function"); } // display() is a method of class base void display() { System.out.println("This is display function of base class"); } } // class base is inherited by class derived class derived extends base { /* display() method is defined again in class derived, thus overriding the definition of display() in class base */ void display() { System.out.println("This is display function of derived class"); } } class poly1 { public static void main(String args[]) { derived d1 = new derived(); // disp() method defined in class base is executed here d1.disp(); /* display() method defined in class derived is executed here, thus overriding the display method in the class base */ d1.display(); } } Output: Base class function This is display function of derived class Given below is another example, which will explain the concept of method overriding: class Parent { int x; Parent(int x) { this.x = x; } // method display() defined void display() { System.out.println("Parent x = " + x); } } // class Parent is inherited by class Child class Child extends Parent { int y; Child (int x, int y) { // calling the Parent class constructor super(x); this.y = y; } // display() method is defined again in class Child void display() { System.out.println("Parent x = " + x); System.out.println("Child y = " + y); } } class OverrideTest { public static void main(String args[]) { Child c1 = new Child(100, 200); /* display() method defined in Child class is executed and it overrides the display() method defined in class Parent */ c1.display(); } } Output: Parent x = 100 Child y = 200 |
Course Content > Session 5 >