In this article we will see 'What is method overriding in Java', and how to use it with example.

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 and this phenomena is called method overriding. Method overriding is also referred to as run time polymorphism.
//Super Class
class Human {
	public String getName() {
		return "Human";
	}
}

// Sub Class
class Male extends Human {
	public String getName() {
		return "Male";
	}
}
While calling getName() with Subclass Object and Reference Variable or Subclass object but Super class Reference variable, method in subclass will be called:
public class Main {
	public static void main(String args[]) {
		Male male = new Male();
		System.out.println(male.getName()); // prints 'Male'

		Human human = new Male();
		System.out.println(human.getName()); // prints 'Male'
	}
}
Note: Static methods cannot be overridden because, a static method is bounded with class where as instance method is bounded with object.

Overriding with different return types

In Java method overriding is possible even if the method in super class and subclass has same name, same number of arguments and same type signature but different return type, the only condition is the return type of subclass must be a child of return type in super class.
//Super Class
class Human {
	public Human getInstance() {
		return new Human();
	}
}

// Sub Class
class Male extends Human {
	public Male getInstance() {
		// return type is subclass of Human
		return new Male();
	}
}

public class Main {
	public static void main(String args[]) {
		Male male = new Male();
		Male male2 = male.getInstance(); // Returns Male's instance
	}
} 
In this article we have seen 'What is method overriding in Java', and how to use it with example. In upcoming articles we will see more about Java.
  • By Techburps.com
  • Nov 7, 2017
  • Core Java