We will discuss here whether we can override static method in Java or not.

If a subclass defines a static method with the same signature as a static method in the superclass, then the method in the subclass hides the one in the superclass.

The distinction between hiding a static method and overriding an instance method has important implications:

  • The version of the overridden instance method that gets invoked is the one in the subclass.
  • The version of the hidden static method that gets invoked depends on whether it is invoked from the superclass or the subclass

Consider an example:

In the below class we have both static and non-static methods.

public class Vehicle {
	public static void classMethod() {
		System.out.println("Super : inside classMethod");
	}
	public void instanceMethod() {
		System.out.println("Super : inside instanceMethod");
	}
}

The below child class extends the above class. We have overridden both methods in the child class.

public class Car extends Vehicle {
	public static void classMethod() {
		System.out.println("Child : inside classMethod");
	}
	public void instanceMethod() {
		System.out.println("Child : inside instanceMethod");
	}
}

Let’s consider the below class with main method:

public class TestMethodOverride {
	public static void main(String[] args) {
		Car car = new Car();
		car.instanceMethod();
		car.classMethod();
		Vehicle vehicle = new Vehicle();
		vehicle.instanceMethod();
		vehicle.classMethod();
		vehicle = car;
		vehicle.instanceMethod();
		vehicle.classMethod();
	}
}

Running the above class, we have the following output:

Child : inside instanceMethod
Child : inside classMethod
Super : inside instanceMethod
Super : inside classMethod
Child : inside instanceMethod
Super : inside classMethod

The Car class overrides the instance method in Vehicle and hides the static method in Vehicle.

The main method in this class creates an instance of Car and invokes classMethod() on the class and instanceMethod() on the instance.

From the above output it is clear that the version of the hidden static method that gets invoked is the one in the super class, and the version of the overridden instance method that gets invoked is the one in the subclass.

Thanks for reading.

Tags:

Leave a Reply

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