Curriculum
Course: Learn Java Programming
Login

Curriculum

Learn Java Programming

Video lesson

Understanding Methods Overridding in Java

In this lesson, you will learn

  • Method Overriding in Java
  • Examples

 

What is Method Overriding?

  • Definition:

    • Method overriding occurs when a subclass provides a different implementation for a method already defined in its superclass.
    • The method in the subclass must have the same name, parameters, and return type as the method in the superclass.  
    • Purpose:

      • It allows subclasses to customize or extend the behavior of inherited methods.
      • It’s a key component of runtime polymorphism, enabling objects of different classes to respond to the same method call uniquely.

    MethodOverriding1

    Important Note!

    When an overridden method is called from within its subclass, it will always refer to the version of that method defined by the subclass. The version of the method defined by the superclass will be hidden.

    Let’s understand method overriding using an example.

    Example 1: Method Overriding

    package ch9.l6;
    
    class First {
    	int i, j;
    	First(int a, int b) {
    		i = a;
    		j = b;
    	}
    	 // display i and j
    	 void show() {
    		 System.out.println("i and j: " + i + " " + j);
    	 }
    	
    }
    
    class Second extends First{
    	int k;
    	Second(int a, int b, int c) {
    		super(a, b);
    		k = c;
    	}
    	
    	 // display k – this overrides show() in A
    	 void show() {
    		 System.out.println("k: " + k);
    	 }
    }
    
    public class MethodOverriding {
    
    	public static void main(String[] args) {
    		Second obj=new Second(10, 20, 30);
    		obj.show();
    	}
    }
    

    Output

    k: 30
    

    Explanation

    When show( ) is invoked on an object of type Second, the version of show( ) defined within Second
    is used. The version of show( ) inside Second overrides the version declared in First.

    If you wish to access the superclass version of an overridden method, you can do so by using super.

    Let’s understand the example below where the superclass version of show( ) is invoked within the subclass version.

     

    class Second extends First{
    	int k;
    	Second(int a, int b, int c) {
    		super(a, b);
    		k = c;
    	}
    	
    	 // display k – this overrides show() in A
    	 void show() {
    		 super.show(); //this calls A's show()
    		 System.out.println("k: " + k);
    	 }
    }
    

     

    If you substitute this version of First into the previous program, you will see the following

    Output

    i and j: 10 20
    k: 30
    

     

    Here, super.show() calls the superclass version of show( ).

     

    Important Note!

    Method overriding occurs only when the names and the type signatures of the two methods are identical. If they are not, then the two methods are overloaded.

     

    Example 2: Method Overloading

    package ch9.l6;
    
    // Methods with differing type signatures are overloaded – not
    // overridden.
    class One {
    	int i, j;
    	One(int a, int b) {
    		i = a;
    		j = b;
    	}
    	 // display i and j
    	 void show() {
    		 System.out.println("i and j: " + i + " " + j);
    	 }
    	
    }
    
    class Two extends One{
    	int k;
    	Two(int a, int b, int c) {
    		super(a, b);
    		k = c;
    	}
    	
    	// overload show()
    	 void show(String msg) {
    		 System.out.println(msg + k);
    	 }
    }
    
    public class Overload {
    
    	public static void main(String[] args) {
    		Two two=new Two(2, 3, 4);
    		two.show("This is k: ");// this calls show() in Two
    		two.show(); // this calls show() in One
    	}
    }
    

    Output

    This is k: 4
    i and j: 2 3
    

     

    Example: Method Overriding ‘Shape Area Calculation’

    Suppose we have a superclass called Shape that defines a method to calculate the area. Different subclasses (e.g., Circle, Square, Rectangle) will override this method to provide their specific calculations for the area.

    Example: Shape Area Calculation

    package ch9.l6;
    
    
    class Shape {
        // Method to calculate area
        double area() {
            return 0;
        }
    }
    
    class Circle extends Shape {
        double radius;
    
        Circle(double r) {
            radius = r;
        }
    
        // Overriding the area method for circle
        double area() {
            return Math.PI * radius * radius;
        }
    }
    
    class Square extends Shape {
    	double side;
    	
    	public Square(double s) {
    		side=s;
    	}
    	
    	// Overriding the area method for square
    	double area() {
            return side*side;
        }
    }
    
    class Rectangle extends Shape {
        double length,width;
    
        Rectangle(double l, double w) {
            length = l;
            width = w;
        }
    
        // Overriding the area method for rectangle
        double area() {
            return length * width;
        }
    }
    
    public class TestShapes {
        public static void main(String[] args) {
            Circle myCircle = new Circle(5);
            Square mySquare = new Square(10);
            Rectangle myRectangle = new Rectangle(4, 5);
    
            System.out.println("Circle area: " + myCircle.area());
            System.out.println("Square area: " + mySquare.area());
            System.out.println("Rectangle area: " + myRectangle.area());
        }
    }
    

    Output

    Circle area: 78.53981633974483
    Square area: 100.0
    Rectangle area: 20.0
    

     

    Key differences between Method Overloading and Method Overriding

    Aspect Method Overloading Method Overriding
    Definition Multiple methods in the same class have the same name but different parameters (type, number, or both). A subclass has a method with the same name, parameters, and return type as a method in its superclass.
    Purpose To achieve compile-time polymorphism. To achieve run-time polymorphism.
    Parameters Must differ in type, number, or both. Must be the same as the method in the superclass.
    Return Type Can be different. Must be the same or covariant (subclass type).
    Scope Within the same class. Across classes (in superclass and subclass).
    Invocation Determined by the reference type of the arguments at compile time. Determined by the object type at runtime.
    Access Modifier Can be different for overloaded methods. Cannot be more restrictive than the overridden method.
    static, final, private Methods Can be overloaded. Cannot be overridden (static methods can be hidden, but that’s not overriding).