Java Design Pattern
Introduction to Java 10
Introduction to Java 11
Introduction to Java 12

Java Method Overriding

When a method name and its signature in both the super and sub class is same, then the method in the sub class is said to be an overridden method.

When the overridden method is called from within a sub class , it always refer to the version of that method defined by the sub class. That means the method defined by the super class will be hidden.

Let us see a program to understand method overriding.


package java8s;

class Vehicle
	void move()
		System.out.println("vehicle is running");
class Car extends Vehicle
	void move()
		System.out.println("car is running");
publicclass MethodOverriddingDemo {

	publicstaticvoid main(String[] args) {
		Car c=new Car();

method overriding

As you can see here Test1 class gives it own implementation of show() method. Method must have same name and same type signature.

Static methods cannot be overridden because, a static method is bounded with class where as instance method is bounded with object.

Difference between method Overloading and Method Overriding in java:

It is one of the common interview questions for freshers.There are three basic differences between the method overloading and method overriding.

Method Overloading Method Overriding
The name of the method must be same
and the signature must be different.
Both name and signature must be same.
Compile time polymorphism. Runtime polymorphism.
Used to readability of code. Used to reusability of code.

Can we override static method ? Explain with reasons:
No, we cannot override static method. Because static method is bound to class whereas method overriding is associated with object i.e at runtime.

About the Author

Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc