The perfect place for easy learning...

Java Programming

×

Topics List


Java Method Overriding





The method overriding is the process of re-defining a method in a child class that is already defined in the parent class. When both parent and child classes have the same method, then that method is said to be the overriding method.

The method overriding enables the child class to change the implementation of the method which aquired from parent class according to its requirement.

In the case of the method overriding, the method binding happens at run time. The method binding which happens at run time is known as late binding. So, the method overriding follows late binding.

The method overriding is also known as dynamic method dispatch or run time polymorphism or pure polymorphism.

Let's look at the following example java code.

Example
class ParentClass{
	
	int num = 10;
	
	void showData() {
		System.out.println("Inside ParentClass showData() method");
		System.out.println("num = " + num);
	}
	
}

class ChildClass extends ParentClass{
	
	void showData() {
		System.out.println("Inside ChildClass showData() method");
		System.out.println("num = " + num);
	}
}

public class PurePolymorphism {

	public static void main(String[] args) {
		
		ParentClass obj = new ParentClass();
		obj.showData();
		
		obj = new ChildClass();
		obj.showData();
		
	}
}

When we run this code, it produce the following output.

polymorphism in java

10 Rules for method overriding

While overriding a method, we must follow the below list of rules.

  • Static methods can not be overridden.
  • Final methods can not be overridden.
  • Private methods can not be overridden.
  • Constructor can not be overridden.
  • An abstract method must be overridden.
  • Use super keyword to invoke overridden method from child class.
  • The return type of the overriding method must be same as the parent has it.
  • The access specifier of the overriding method can be changed, but the visibility must increase but not decrease. For example, a protected method in the parent class can be made public, but not private, in the child class.
  • If the overridden method does not throw an exception in the parent class, then the child class overriding method can only throw the unchecked exception, throwing a checked exception is not allowed.
  • If the parent class overridden method does throw an exception, then the child class overriding method can only throw the same, or subclass exception, or it may not throw any exception.