Java Overriding

Overriding is one of the important concept in Polymorphism. In Inheritance, say if a sub class has different implementation of one of the certain method in the parent class, then it needs to be overrided in the sub class.


Overriding:

The overriding method in the subclass should have same name, number and type of parameters and the return type similar to the method in the parent class.

For the abstract methods and for the interface methods, it is mandatory to override and implement the methods in the subclass.

 

Sample Program:

HumanBeing.java


public class HumanBeing {
	
	public static void main(String[] args) {
		
		Male john = new Male();
		john.sing();		
	}	
	
	public void sing() {
		System.out.println("I am singing.");		
	}
}

In the above parent (HumanBeing) class, there is a method called sing() which is applicable to both male and female child classes. The functionality that the method does is to print “I am singing.”. Assume that we are having a requirement for the male object to print both “I am singing.” & “Hi I am a male singer.” sentences when the sing() method is called. Then we might need to override the sing method in the male class in order to achieve this requirement. The male.java class file would be as follows.

Male.java


public class Male extends HumanBeing {
	
	public void sing(){
		super.sing();
		System.out.println("Hi I am a male singer.");		
	}	
}

Output:

I am singing.
Hi I am a male singer.

 

Posted on July 1, 2014 in Java for Beginners

Share the Story

Leave a reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Back to Top