Method overriding in Java with 4 real time examples

(Last Updated On: February 26, 2019)

Learn method overriding in java language with 4 real time examples. All examples are simulated with working pseudo programs and explained scenario.

Method overriding in java oops is run time polymorphism and is always implemented in inheritance relationship. Inheritance relationship can be in between base class and derived class or between interface and its sub classes in java programming.

In below image, we can see how we override methods of a base class in to a child class. And, also override method of an interface by implementing in sub class.

method overriding in java

Method overriding feature gives ability to a child class to define its own behavior if It does not want to use parent class behavior.Meaning, a child class can write a method with same name that is also in base class and implement it. it is called method overriding in java oops.

 

Method overriding in java with simple example

Lets consider an example that, A Son inherits his Father’s public properties e.g. home and car and using it. At later point of time, he decided to buy and use his own car, but, still he wants to use his father’s home. So, what he can do?

He can use method overriding feature and use his own car.  See below example, how he has overridden his own car method. He is not supposed to destroy his father car. right? Once you create the object of Son and call home and car methods. Father’s home and Son’s car will be called.

 

Example of method overriding using Parent class and child

 class Father{
	
	public void home(){
		System.out.println("Father's home");
	}
	public void car(){
		System.out.println("Father's Car");
	}	
}
class Son extends Father{
	
	@Override
	public void car() {
		System.out.println("Son's Car");		
	}	
}
public class TestOverriding {

	public static void main(String[] args) {
		
		Son s = new Son();
		s.home();
		s.car();
	}

}

 

Output:
Father’s home
Son’s Car

 

So for, we understand that a child class can override a method of a parent class and can give its own definition.

Similarly, if we have an interface, the class who inherit and implement the interface, class must override all methods of the interface.

In below class we have Shape interface with a draw () method.  The class Circle will override the method of interface and implement it.

Note that an interface has only abstract methods that is not implemented or say does not have definition or implementation. You can read here complete tutorial on interface in java with example.

 

Example of method overriding in java using Parent Interface and subclass

//interface
interface Shape{
	void draw();
}
//class override draw() method and implement it
class Circle implements Shape{

	@Override
	public void draw() {		
		System.out.println("Circle...");
	}	
}

public class TestOverriding {

	public static void main(String[] args) {		
		Shape circle = new Circle();
		circle.draw();
	}

}

Output:
Circle…

 

 

As a conclusion,

  • Don’t want to use some of the base class methods? Use feature method overriding in java programs. Write those methods with same name in your class and implement them. Whenever you call those methods with your objects then your methods will be called or else base class method will be called.
  • Do you have an interface and want to use all its methods to be implemented? Create a class, inherit the interface using implements keyword and override all its methods and implement it in the class.

 

 

Now let’s read some simulated real-life examples where method overriding is required. All pseudo code is extracted from real life projects.

Scenarios when method overriding in java oops is required

  • Change Requirements
  • Need contracts in Interface and abstract classes
  • Code extendibility
  • Achieve loose coupling

 

Example -1: Using method java method overriding on Change Requirement

Method overriding in java when change requirements occur – There are two music companies Sony and Panasonic. They want to use a third-party music library. They are using all operations (methods) from Music class. To make the program simple and understandable, let’s say Music class provides music initialization and one of the methods i.e. play() method.

Both Sony and Panasonic companies using play method of Music class. After years, Sony decided that all the methods from the music class will be used but it will no longer use the play method for some reason. But, Panasonic and other companies want to use the library’s play method.

So, Sony overrides the play method and provide its own implementation. Whereas other companies continue using the paly method of Music class from third party. so, they don’t override it.

 

/*---------------------------------------------------
 * Music class from third party library
 * */
class Music {

	Music() {
		System.out.println("Music::Initializing song...");
	}

	public void play() {
		System.out.println("Music:: Playing music...");
	}
}

/*----------------------------------------------------
 * Sony company wants to use his own play() method for some
 * reason not from the third partly, so it overrides this methods
 * and gives his own definition to it.
 */
class Sony extends Music {

	Sony() {
		System.out.println("Sony operations...");
	}

	@Override
	public void play() {
		System.out.println("Sony:: Playing music... ");
	}

}

/*----------------------------------------------------
 * Panasonic company wants to use play() method from
 * the third partly
 */
class Panasonic extends Music {

	Panasonic() {
		System.out.println("Panasonic operations...");
	}
}

/**
 * ----------------------------------------------- Test music
 * 
 */
public class Player {
	public static void main(String... args) {

		System.out.println("Sony :: ");
		Sony s = new Sony();
		s.play();

		System.out.println("\nPanasonic :: ");
		Panasonic p = new Panasonic();
		p.play();

	}
}

 

 

Example -2: Java method overriding on need of contracts in Interface and abstract classes

  1. a) Example of overriding interface methods.

Let’s say Samsung company requested Dell company to provide support for Samsung mouse to Dell laptops.

Dell agreed on that and ask Samsung to implement his contracts to give support as per their design. Dell gives contracts in an interface to Samsung as given below.

 

interface Mouse{
	void leftClick();
	void rightClick();
	void scroll();
}

 

Now Samsung will implement these contracts. Meaning, mouse classes will inherit the interface by using implements keyword and override all methods and implement them in the class. for example

 

interface Mouse{
	void leftClick();
	void rightClick();
	void scroll();
}

//Samsung mouse class override all methods of
//interface and implement them
class ClassicMouse implements Mouse{

	@Override
	public void leftClick() {		
		System.out.println("Left Click...");
	}

	@Override
	public void rightClick() {	
		System.out.println("Righ Click...");
	}

	@Override
	public void scroll() {		
		System.out.println("Scroll ...");
	}	
}

//Test
public class Test {

	public static void main(String[] args) {
		
		Mouse m = new ClassicMouse();
		m.leftClick();
		m.rightClick();
		m.scroll();
	}

}

 

 

b) Example of overriding abstract methods. – Vending machine design

public abstract class Bevarages {


	/* Common methods that will be used by sub classes*/
	public void boilMilk(){
		System.out.println("milk");
	}
	public void suger(){
		System.out.println("suger");		
	}	
	
	public void hotWater(){
		System.out.println("hot water");
	}
	/* Force subclasses to override and implement it*/
	public abstract void ingredient();
}

//Tea class extends abstract class Bevarages and 
//override abstract method ingredient() and implement it.
public class Tea extends Bevarages {

	@Override
	public
	void ingredient() {
		
		System.out.println("TEA");
	}
	
}

public class Coffee extends Bevarages{
	//Coffee class extends abstract class Bevarages and 
	//override abstract method ingredient() and implement it.
	@Override
	public
	void ingredient() {
		System.out.println("Coffee");		
	}

}

public class VendingMachine {

	
	public static void main(String[] args) {
		

		/* ----  Prepare tea -----------------*/
		System.out.println("Serve Tea : ");
		Bevarages tea = new Tea();
		tea.hotWater();
		tea.boilMilk();
		tea.suger();
		tea.ingredient();
		
		/* ----  Prepare Coffee -----------------*/
		System.out.println("\nServe Coffee : ");
		Bevarages coffee = new Coffee();
		coffee.hotWater();
		coffee.boilMilk();
		coffee.suger();
		coffee.ingredient();
	}

}

 

 

Example-3: Method overriding in java oops on Code extendable

Method overriding in java applications to make code extendable – Consider a Game that comprises many scenes like house, bus stop and supper market etc. As a good design, scenes should be extendable. So, we can create an interface Scene and extend multiple types of scenes. All scenes i.e. house and super market will override and implement the interface methods.

for example, in below java source code. House and SuperMarket class have override and implemented display() method of interface.

 

/*
 * Example of overriding of interface methods
 * 
 * All subclasses will override and implement
 * display method
 */
interface Scene{
	void display();
}

class House implements Scene{

	@Override
	public void display() {
			System.out.println("House Scene");	
	}	
}

class SuperMarket implements Scene{

	@Override
	public void display() {
			System.out.println("Super Market Scene");	
	}	
}
public class Game {
	
	public static void main(String[] args) {
		
		Scene house = new House();
		house.display();
		
		Scene sm = new SuperMarket();
		sm.display();

	}

}

 

Output:
House Scene
Super Market Scene

 

 

Example-4: Java method overriding to achieve loose coupling example

Method overriding in java to achieve loose coupling – Consider a very complex existing manager class that is handling multiple types of working. We might not be interested to modify the manager class again and again whenever we must add a new types workers time to time. We know that in real time software product, even though we change a little in existing class, entire class need to be tested.

Note that loose coupling means reducing dependencies of a class that use different class directly. Tight coupling means classes and objects are dependent on one another.

In given scenario, if Manage class compose multiple types of workers then it would be tightly coupled code and when new type of worker is required, we must change the class. It is better to have an interface and let all types of workers implement and override its methods. Read comparison example of tight coupling and loose coupling.