by BehindJava

What is method overriding in Java

Home » java » What is method overriding in Java

In this tutorial, we are going to learn what is method overriding.

The name method overriding itself explains that a method is being overridden and in the object oriented programming we can achieve it by the inheritance where child object acquires all the properties upon extending the parent class.

When a child class has the same method name that is already defined in the parent class is called method overriding. Method overriding is also used to achieve runtime polymorphism also known as dynamic method dispatch. Upcasting is process in which a reference variable of parent class refers to the object of child class.

Sample Code Snippet:

public class ParentConnection
	{
		public void connect()
		{
			System.out.println("CONNECT TO ACT WIFI ");
		}
	}
	public class ChildConnection extends ParentConnection
	{
		public void connect()
		{
			System.out.println("CONNECT TO JIO WIFI ");
		}
		public static void main(String[] args)
		{
			//Upcasting based on the requirement
			//case 1
			ParentConnection pc=new ChildConnection();
			pc.connect();
			//case 2
			ParentConnection pc=new ParentConnection();
			pc.connect();
			//case 3
			ChildConnection pc=new ChildConnection();
			pc.connect();
			//case 4
			ChildConnection pc=new ParentConnection();
			pc.connect();
		}
	}

In the above code snippet, There is parent class named ParentConnection which has a method that connects user to ACT WIFI, Now I have a child class ChildConnection which needs to connect to JIO WIFI.

So based on the requirement we need to call the connect method using upcasting.

Case 1:

ParentConnection pc=new ChildConnection();
			pc.connect();

A reference of parent class is created that refers to the child class object and connect method in the child class is called.
Output :
CONNECT TO JIO WIFI

Case 2:

ParentConnection pc=new ParentConnection();
			pc.connect();

This is pretty straight, where reference and object of parent class is created.
Output:
CONNECT TO ACT WIFI

Case 3:

ChildConnection pc=new ChildConnection();
			pc.connect();

Again this is same as case 2 where reference and object are created for child class.
Output:
CONNECT TO JIO WIFI

Case 4:

ChildConnection pc=new ParentConnection();
			pc.connect();

In this case, compiler shows the error message “Type mismatch: cannot convert from ParentConnection to ChildConnection”. Since upcasting only happens for parent reference to child object but not from child reference to parent.

Case 2 and case 3 are examples of Static binding.
When type of the object is determined at compiled time(by the compiler), it is known as static binding.
If there is any private, final or static method in a class, there is static binding.

Case 1 is the example of Dynamic binding.
When type of the object is determined at run-time, it is known as dynamic binding.