Method Overriding in Java

Method overriding is one of the importance concept in Java Programming.

What is Method Overriding?

In Inheritance hierarchy when a child class defines exact same method that is available in parent class then the method is called overridden method.

The process of creating overridden method is called method overriding.

class Shape {
    void draw() {
        System.out.println("Draw Shape");
    }
}
class Triangle extends Shape {
    void draw() {
        System.out.println("Draw Triangle Shape");
    }
}
class Rectangle extends Shape {
    void draw() {
        System.out.println("Draw Rectangle Shape");
    }
}
class Circle extends Shape {
    void draw() {
        System.out.println("Draw Circle Shape");
    }
}
public class MyClass {
    public static void main(String args[]) {
        Shape shape = new Shape();
        shape.draw();
        Triangle triangle = new Triangle();
        triangle.draw();
        Rectangle rectangle = new Rectangle();
        rectangle.draw();
        Circle circle = new Circle();
        circle.draw();
    }
}

Result

 
Draw Shape
Draw Triangle Shape
Draw Rectangle Shape
Draw Circle Shape

We have created a class Shape.

Also created child classes Triangle, Rectangle and Circle.

On child class we have created same method draw(). Creating exact same method in child is known as method overriding.

In child class method signature and return type is exact same as parent but child class provides new definition to overridden method.

Why method overriding?

When defined method in parent class is not suitable for child class then we override method.

As in above example method draw() is overridden in all child class.

Because draw() behaves differently for different classes.

Note: If we want to access the super class overridden method, we can do so by using super keyword.

void show() {
        super.show();//this call’s A’s show();
        System.out.println(" Class B ");
    }
 
Inside display
 Class A
 Class B 




Note: Overriding occurs only when the method name and parameter list of the method are identical.  

Method with same name and different parameter list are simply overloaded not overridden.

 
class A {

    void show() {
        System.out.println("Inside Class A show method");
    }
}

class B extends A {

    void show(int a) { // overload show()	
        System.out.println("Indide class B show method");

    }
}

public class abc {

    public static void main(String arg[]) {
        B objB = new B();
        objB.show();		// this calls show() of class A  
        objB.show(10);		// this calls show() of class B	
    }
}

Result

 
Inside Class A show method
Indide class B show method