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

Plus Minus HackerRank Solution in Java | Programming Blog

Java Solution for HackerRank Plus Minus Problem Given an array of integers, calculate the ratios of its elements that are positive , negative , and zero . Print the decimal value of each fraction on a new line with 6 places after the decimal. Example 1 : array = [1, 1, 0, -1, -1] There are N = 5 elements, two positive, two negative and one zero. Their ratios are 2/5 = 0.400000, 2/5 = 0.400000 and 1/5 = 0.200000. Results are printed as:  0.400000 0.400000 0.200000 proportion of positive values proportion of negative values proportion of zeros Example 2 : array = [-4, 3, -9, 0, 4, 1]  There are 3 positive numbers, 2 negative numbers, and 1 zero in array. Following is answer : 3/6 = 0.500000 2/6 = 0.333333 1/6 = 0.166667 Lets see solution Solution 1 import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.regex.*; import java.util.stream.*; import static jav...

Flipping the Matrix HackerRank Solution in Java with Explanation

Java Solution for Flipping the Matrix | Find Highest Sum of Upper-Left Quadrant of Matrix Problem Description : Sean invented a game involving a 2n * 2n matrix where each cell of the matrix contains an integer. He can reverse any of its rows or columns any number of times. The goal of the game is to maximize the sum of the elements in the n *n submatrix located in the upper-left quadrant of the matrix. Given the initial configurations for q matrices, help Sean reverse the rows and columns of each matrix in the best possible way so that the sum of the elements in the matrix's upper-left quadrant is maximal.  Input : matrix = [[1, 2], [3, 4]] Output : 4 Input : matrix = [[112, 42, 83, 119], [56, 125, 56, 49], [15, 78, 101, 43], [62, 98, 114, 108]] Output : 119 + 114 + 56 + 125 = 414 Full Problem Description : Flipping the Matrix Problem Description   Here we can find solution using following pattern, So simply we have to find Max of same number of box like (1,1,1,1). And ...