Skip to main content

Method Overriding in Java with examples and Rules | covariant return type

In this blog we learn about,

  1. What is Method overriding
  2. What is covariant return type
  3. How we can use access modifier in method overriding
  4. How exception works with overriding
  5. How overriding works with static, final and var-args methods
Method in Overriding Java with examples and Rules

What is Method Overriding in Java?

In simple terms, When a method in subclass have same method name, same arguments (parameters) and same return type same as its super or parent class its called Method Overriding.

Overriding is a feature that allows a sub class or child class to provide specific method implementation that is already provided in its parent class or super class.

Lets see simple example of Method Overriding.

Example 1 : Method Overriding demo

SuperClass.java 

public class SuperClass {

    // Overridden Method
    public void OverRideMethod() {
        System.out.println("Super or Parent Class");
    }
}

SubClass.java

public class SubClass extends SuperClass {
    
    // Overriding Method
    public void OverRideMethod() {
        System.out.println("Sub or Child Class");
    }

    public static void main(String[] args) {
       
        SuperClass obj1 = new SuperClass();
        obj1.OverRideMethod();
       
        SubClass obj2 = new SubClass();
        obj2.OverRideMethod();
       
        SuperClass obj3 = new SubClass();
        obj3.OverRideMethod();

    }

}

Output :

Super or Parent Class
Sub or Child Class
Sub or Child Class

In method overriding method resolution done at run time so method overriding also called Run time polymorphism, Dynamic polymorphism or late binding.

Lets see key point or rules of method overriding.

Rules of Method Overriding

1 : In method overriding, method signature must be same.

Means sub class must have same method name with same argument types and its data type.

2 : Return type of Overridden methods must be same (or subtype)

Before Java 5.0, when you override a method, both parameters and return type must match exactly. Java 5.0 it introduces a new facility called covariant return type.  

Means overriding method can use covariant return type. lets se example for better understanding.

Example 2 : Return type in Method Overriding

public class SuperClass {

    public Object OverRideMethod() {
        return "Super or Parent Class";
    }
}

public class SubClass extends SuperClass {
    
    public String OverRideMethod() {
        return "Sub or Child Class";
    }
}

We can also take Integer, Float, Double or any other return type who is child of Object class. 

Covariant return type is allowed only for Object types, it is not allowed in Primitive data types.

Means if parent class method has return type double and child class return type has int, then this is not allowed.

Learn more about covariant return type in java :

3 : Private method is not applicable for method overriding

If parent and child class both contains same method signature but access modifier is private then it is not called method overriding.

4 : Final methods can not be overridden

If we try to override final method compiler gives compile time error.

In eclipse when we try to override final method it gives following error.

Final method can not be overridden in java

5 : Access modifier in Method Overriding

The access modifier for an overriding method can allow more, but not less, access than the overridden method. For example, if super class have public method and child class have protected method then it will generate compile-time error.

Reducing scope by overriding method is not allowed.

  • private < default < protected < public

Compiler gives error when we try to write less scope modifier.

Reducing scope by overriding method is not allowed.

Increasing scope in override method is valid. means if parent class method have protected and child class have public modifier override method then it is valid.

Parent class    Child class

public    ->    public 

protected    ->    protected, public

default    ->    default, protected, public

6 : Overriding and Exception handling

When child class throws any checked exception, parent class must throws checked exception or its parent. otherwise compiler gives error. There is no rule for unchecked exception.

Overriding and Exception handling

Learn more about Checked and Unchecked Exception :

7 : Overriding and Static methods

We can not override static method with non static and non static method with static method. If we try to do that compiler gives error.

If parent and child both class contain same method signature and it is static then it is called Method Hiding.

In method hiding, method resolution done by compiler based on reference type.

Lets see example.

Example 3 : Overriding static methods (Method hiding)

SuperClass.java

public class SuperClass {

    public static void OverRideMethod() {
        System.out.println("Super or Parent Class");
    }
}

SubClass.java

public class SubClass extends SuperClass {
    
    public static void OverRideMethod() {
        System.out.println("Sub or Child Class");
    }

    public static void main(String[] args) throws IOException {
       
        SuperClass obj1 = new SuperClass();
        obj1.OverRideMethod();
       
        SubClass obj2 = new SubClass();
        obj2.OverRideMethod();

        SuperClass obj3 = new SubClass();
        obj3.OverRideMethod();
       
    }

Output :

Super or Parent Class
Sub or Child Class
Super or Parent Class

In above example of method hiding, when we create SuperClass reference and SubClass object then it is calling Parent class method.

8 : var-args methods with overriding

We can not override var-args methods with non var-args method. If we try to do that then it is not called overriding. 

If we want to override var-args methods, then we can override with only var-args methods.

Example 4 : Overriding var-args methos with non var-args method

public class SuperClass {

    public void OverRideMethod(int... args) {
        System.out.println("Super or Parent Class");
    }
}

public class SubClass extends SuperClass {
    
    public void OverRideMethod(int args) {
        System.out.println("Sub or Child Class");
    }

    public static void main(String[] args) {
        
        SuperClass obj1 = new SuperClass();
        obj1.OverRideMethod(10);
        
        SubClass obj2 = new SubClass();
        obj2.OverRideMethod(20);

        SuperClass obj3 = new SubClass();
        obj3.OverRideMethod(30);
        
    }
}

Output :

Super or Parent Class
Sub or Child Class
Super or Parent Class

Example 5 : Overriding var-args methods

public class SuperClass {

    public void OverRideMethod(int... args) {
        System.out.println("Super or Parent Class");
    }
}

public class SubClass extends SuperClass {
    
    public void OverRideMethod(int... args) {
        System.out.println("Sub or Child Class");
    }

    public static void main(String[] args) {
        
        SuperClass obj1 = new SuperClass();
        obj1.OverRideMethod(10);
        
        SubClass obj2 = new SubClass();
        obj2.OverRideMethod(20);

        SuperClass obj3 = new SubClass();
        obj3.OverRideMethod(30);
        
    }
}

Output :

Super or Parent Class
Sub or Child Class
Sub or Child Class

 
Learn about Method Overloading in Java :

Comments

Popular posts from this blog

Sales by Match HackerRank Solution | Java Solution

HackerRank Sales by Match problem solution in Java   Problem Description : Alex works at a clothing store. There is a large pile of socks that must be paired by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are. For example, there are n=7 socks with colors socks = [1,2,1,2,1,3,2]. There is one pair of color 1 and one of color 2 . There are three odd socks left, one of each color. The number of pairs is 2 .   Example 1 : Input : n = 6 arr = [1, 2, 3, 4, 5, 6] Output : 0 Explanation : We have 6 socks with all different colors, So print 0. Example 2 : Input : n = 10 arr = [1, 2, 3, 4, 1, 4, 2, 7, 9, 9] Output : 4 Explanation : We have 10 socks. There is pair of color 1, 2, 4 and 9, So print 4. This problem easily solved by HashMap . Store all pair of socks one by one in Map and check if any pair is present in Map or not. If pair is present then increment ans variable by 1 ...

Queen's Attack II HackerRank Solution in Java with Explanation

Queen's Attack II Problem's Solution in Java (Chessboard Problem)   Problem Description : You will be given a square chess board with one queen and a number of obstacles placed on it. Determine how many squares the queen can attack.  A queen is standing on an n * n chessboard. The chess board's rows are numbered from 1 to n, going from bottom to top. Its columns are numbered from 1 to n, going from left to right. Each square is referenced by a tuple, (r, c), describing the row r and column c, where the square is located. The queen is standing at position (r_q, c_q). In a single move, queen can attack any square in any of the eight directions The queen can move: Horizontally (left, right) Vertically (up, down) Diagonally (four directions: up-left, up-right, down-left, down-right) The queen can move any number of squares in any of these directions, but it cannot move through obstacles. Input Format : n : The size of the chessboard ( n x n ). k : The number of obstacles...