Home » Java » Method Overriding in Java

Method Overriding in Java

What is Method Overriding?

In java if subclass contains same method as declared in the parent class then it is known as method overriding.Method in a subclass has the same name, same parameters or signature and same return type(or sub-type) as a method in its super-class, then the method in the subclass is said to override the method in the super-class.

Sometimes, the sub class may want to provide a specific implementation of methods defined in the super class, it is referred as method overriding. Method overriding allows a sub class to provide its own implementation of a method already provided by one of its super classes.

Method overriding is one of the way by which java achieve Run Time Polymorphism.

Example of method overriding

In this example Dog class extends Animal class. Animal is parent class and it contains run() method. Dog class is overriding run() method and providing its own implementation of run() method.


class Animal{
public void run()
{
System.out.println("Animal is running");
}
}


class Dog extends Animal{
public void run(){
System.out.println("Dog is running");
}
public static void main( String args[]) {
Dog obj = new Dog();
obj.run();
}

Output

Dog is running

Advantage of method overriding

The main advantage of method overriding is that the class can give its own specific implementation to a inherited method without modifying the parent class.

Method Overriding Rules

  1. Child class Method name must be same as the parent class.
  2. Method must have same argument as in the parent class.The data types of the arguments and their order should be maintained as it is in the overriding method(child class method).
  3. A method declared final cannot be overridden.
  4. Constructors cannot be overridden.
  5. A method declared static cannot be overridden but can be re-declared. We will discuss this in separate topic.
  6. Private methods can not be overridden : Private methods cannot be overridden as they are bonded during compile time.
  7. Subclass method access specifier must be same as super class method access specifier or higher than super class method specifier For e.g. if the Access specifier of parent class method is public then the overriding method (child class method ) cannot have private, protected and default Access specifier as all of the three are more restrictive than public.

Super ClassSubclass
PrivatePrivate, default ,protected ,public
defaultdefault ,protected ,public
protectedprotected ,public
publicpublic

Example:


1 . InValid Override :


class Animal{

public void run()

{

System.out.println("Animal is running");

}

}

class Dog extends Animal{

protected void run(){

System.out.println("Dog is Running");

}

public static void main( String args[]) {

Dog obj = new Dog();

obj.run();

}

}

Output

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	Cannot reduce the visibility of the inherited method from Animal

	at com.example.Dog.run(Dog.java:16)
	at com.example.Dog.main(Dog.java:26)

Above code is not a valid override as child class run() method is more restrictive(protected) than base class(public).

1 . Valid Override :


class Animal{

protected void run()

{

System.out.println("Animal is running");

}

}

class Dog extends Animal{

public	void run(){

System.out.println("Dog is Running");

}

public static void main( String args[]) {

Dog obj = new Dog();

obj.run();

}

}

Output

Dog is Running

Above code is perfectly valid scenario as public is less restrictive than protected. Same access modifier is also a valid case of override.

Method Overriding and Exception-

Be careful while handling exception in method overriding. If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception but it can declare unchecked exception.If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent of the exception.Which means if overridden method throws IOException than overriding method can not throw java.lang.Exception in its throws clause because java.lang.Exception comes higher than IOException in Exception hierarchy.

Below are two rules to note when overriding methods related to exception-handling.

  • Rule 1 : If the super-class overridden method does not throws an exception, subclass overriding method can only throws the unchecked exception, throwing checked exception is not allowed in this case and it will lead to compile-time error.

/* Java program to demonstrate overriding when  
  superclass method does not declare an exception 
*/
  
class Parent { 
    void m1() 
    { 
        System.out.println("From parent m1()"); 
    } 
  
    void m2() 
    { 
        System.out.println("From parent  m2()"); 
    } 
} 
  
class Child extends Parent { 
    @Override
    // no issue while throwing unchecked exception 
    void m1() throws ArithmeticException 
    { 
        System.out.println("From child m1()"); 
    } 
  
    @Override
    // compile-time error 
    // issue while throwin checked exception 
    void m2() throws Exception 
    { 
        System.out.println("From child m2"); 
    } 
} 

Output:


error: m2() in Child cannot override m2() in Parent
    void m2() throws Exception{ System.out.println("From child m2");}
         ^
  overridden method does not throw Exception
  
  • Rule 2 : If the super-class overridden method does throws an exception, subclass overriding method can only throw same, subclass exception. Throwing parent exception in Exception hierarchy will lead to compile time error.Also there is no issue if subclass overridden method is not throwing any exception.

// Java program to demonstrate overriding when 
// superclass method does declare an exception 

class Parent { 
	void m1() throws RuntimeException 
	{ 
		System.out.println("From parent m1()"); 
	} 
} 

class Child1 extends Parent { 
	@Override
	// no issue while throwing same exception 
	void m1() throws RuntimeException 
	{ 
		System.out.println("From child1 m1()"); 
	} 
} 
class Child2 extends Parent { 
	@Override
	// no issue while throwing subclass exception 
	void m1() throws ArithmeticException 
	{ 
		System.out.println("From child2 m1()"); 
	} 
} 
class Child3 extends Parent { 
	@Override
	// no issue while not throwing any exception 
	void m1() 
	{ 
		System.out.println("From child3 m1()"); 
	} 
} 
class Child4 extends Parent { 
	@Override
	// compile-time error 
	// issue while throwing parent exception 
	void m1() throws Exception 
	{ 
		System.out.println("From child4 m1()"); 
	} 
} 

Output:


error: m1() in Child4 cannot override m1() in Parent
    void m1() throws Exception
         ^
  overridden method does not throw Exception
  

Difference between method overloading and Method overriding

SNOMethod OverloadingMethod Overriding
1 In Method Overloading, Methods of the same class shares the same name but each method must have different number of parameters or parameters having different types and order. In Method Overriding, sub class have the same method with same name and exactly the same number and type of parameters and same return type as a super class.
2 Overloading happens at compile-time. Overriding happens at runtime.
3 In Method Overloading, methods must have different signature. In Method Overriding, methods must have same signature.
4 static method can be overloaded. you can not override static method in Java. In fact when you declare same method in Sub Class it's known as method hiding because it hide super class method instead of overriding it.
5 private and final method can be overloaded. private and final method can not be overridden.


Previous Next Article

comments powered by Disqus