See the Tutorial List

Method Overriding in Java

When a method in a sub class has same name, same number of arguments and same type signature as a method in its super class, then the method is known as overridden method. Method overriding is also referred to as runtime polymorphism. The key benefit of overriding is the abitility to define method that's specific to a particular subclass type.


Example of Method Overriding

Below we have simple code example with one parent class and one child class wherein the child class will override the method definition provided by the parent class.

class Animal
{
    public void eat()
    {
        System.out.println("Generic Animal eating");
    }
}

class Dog extends Animal
{
    public void eat()   //eat() method overriden by Dog class.
    {
        System.out.println("Dog eat meat");
    }
}

As you can see here Dog class gives it own implementation of eat() method. For method overriding, the method must have same name and same type signature in both parent and child class.

NOTE: Static methods cannot be overridden because, a static method is bounded with class where as instance method is bounded with object.


Covariant return type

Since Java 5, it is possible to override a method by changing its return type. If subclass override any method by changing the return type of super class method, then the return type of overriden method must be subtype of return type declared in original method inside the super class. This is the only way by which method can be overriden by changing its return type.

Example :

class Animal
{
    Animal myType()
    {
        return new Animal();
    }
}

class Dog extends Animal
{
    Dog myType()     //Legal override after Java5 onward
    {
        return new Dog();
    }
}

Difference between Overloading and Overriding

Method overloading and Method overriding seems to be similar concepts but they are not. Let's see some differences between both of them:

Method Overloading Method Overriding
Parameter must be different and name must be same. Both name and parameter must be same.
Compile time polymorphism. Runtime polymorphism.
Increase readability of code. Increase reusability of code.
Access specifier can be changed. Access specifier cannot be more restrictive than original method(can be less restrictive).
It is Compiled Time Polymorphism. It is Run Time Polymorphism.
It is performed within a class It is performed between two classes using inheritance relation.
It is performed between two classes using inheritance relation. It requires always inheritance.
It should have methods with the same name but a different signature. It should have methods with same name and signature.
It can not have the same return type. It should always have the same return type.
It can be performed using the static method It can not be performed using the static method
It uses static binding It uses the dynamic binding.
Access modifiers and Non-access modifiers can be changed. Access modifiers and Non-access modifiers can not be changed.
It is code refinement technique. It is a code replacement technique.
No keywords are used while defining the method. Virtual keyword is used in the base class and overrides keyword is used in the derived class.
Private, static, final methods can be overloaded Private, static, final methods can not be overloaded
No restriction is Throws Clause. Restriction in only checked exception.
It is also known as Compile time polymorphism or static polymorphism or early binding It is also known as Run time polymorphism or Dynamic polymorphism or Late binding

Example

                    
class OverloadingDemo{  
static int add1(int x,int y){return x+y;}  
static int add1(int x,int y,int z){return x+y+z;}  
}                      
                

Example:

                    
class Demo2{  
void a()
{System.out.println("A");}}  
class b extends c
{void a(){System.out.println("B”);}  
                    
                

difference between overloading and overriding


Q. Can we Override static method? Explain with reasons?

No, we cannot override static method. Because static method is bound to class whereas method overriding is associated with object i.e at runtime.


Overriding toString()

Below is an example of the overriding toString() method.

Example:

    
class Demo{
    private double a, b;     
    public Demo(double a, double b) 
    { 
    this.a = b; 
    this.a = b; 
    }  
}
public class MethodDemo11{ 
    public static void main(String[] args) 
    { 
    Demo obj1 = new Demo(25, 10); 
System.out.println(obj1); 
    } 
}
    

string-overriding

In the above example we can see that in java that the default toString() method in object prints “class_name @ hash code”

To override toString() method in a class below is an example

Example

    
class Demo{
    private double a, b;     
    public Demo(double a, double b) 
    { 
    this.a = a; 
    this.b = b; 
    } 
 @Override
    public String toString() 
   { 
        return String.format(a + " + i" + b); 
    }  
}
public class MethodDemo11{ 
    public static void main(String[] args) 
    { 
    Demo obj1 = new Demo(25, 10); 
System.out.println(obj1); 
    
    } 
}
    

string-overriding


Overriding equals method

Below is an example of the overriding equals method.

Example:

    
class Demo{
    private double a, b;    
    public Demo(double a, double b) { 
this.a = b; 
this.a = b; 
    } 
} 
public class MethodDemo11{ 
    public static void main(String[] args) 
    { 
    Demo obj1 = new Demo(25, 10); 
    Demo obj2 = new Demo(25, 10); 
    if (obj1 == obj2) 
        { 
        System.out.println("Values are Equal"); 
        } 
            else 
        { 
        System.out.println("Values are Not Equal"); 
        } 
    } 
}
    

overriding-equal-method

In the above example, we can see that the output is wrong because obj1 and obj2 refer to two different objects that is why (obj1 = = obj2) is false.

To solve this problem below is an example

Example:

    
class Demo{
    private double a, b;    
    public Demo(double a, double b) 
    { 
    this.a = b; 
    this.a = b; 
    }  
@Override
    public booleanequals(Object xyz)
    {
        if (xyz == this) 
        { 
        return true; 
    }  
    if (!(xyz instanceof Demo)) 
        { 
        return false; 
    }  
         Demo obj = (Demo) xyz; 
     return Double.compare(a, obj.a) == 0 &&Double.compare(b, obj.b) == 0; 
    }

}
public class MethodDemo11{ 
    public static void main(String[] args) 
    { 
    Demo obj1 = new Demo(25, 10); 
    Demo obj2 = new Demo(25, 10); 
    if (obj1.equals(obj2)) 
        { 
        System.out.println("Values are Equal"); 
    } 
        else 
        { 
        System.out.println("Values are Not Equal"); 
    } 
    } 
}
    

overriding-equal-method