Site icon TestingDocs.com

Java Method Overriding

Overview

In this tutorial, we will learn Java method overriding. Method overriding allows subclasses to have different implementations for the parent class non-final methods.

Do not get confused with Method overloading.

https://www.testingdocs.com/java-method-overloading/

Java Method Overriding

Overridden method in the child class should have the same name and method signature as that of the super class. However, overridden method can provide different implementation code for the method.

We can use the @Override annotation to indicate that the child method declaration is intended to override a method declaration in a super class/ classes.

Example

A simple example to understand the method overriding concept.

public class BaseClass {

	public void print() {
		System.out.println("This is Base class method");
	}
}



public class ChildClass extends BaseClass {

	public static void main(String[] args) {
		//Demo overridden method
		BaseClass b = new BaseClass();
		ChildClass c = new ChildClass();
		b.print();
		c.print();
	}

	@Override
	public void print() {
		System.out.println("This is Child class method");
	}

}


Sample Output

This is Base class method
This is Child class method

 

Notice how the child method overrides the parent class method. The same method print() works in different ways based on the object types. In the next example, we will look into a more real world example of method overriding.

final method

Note that we cannot override final methods of a class in the child class. We can use the final keyword in a method signature to indicate that the method cannot be overridden by the child classes.

We generally mark methods as final to avoid undesirable re-implementations of the method in the sub classes.

public final void finalMethod() {
System.out.println("Child classes cannot override "
+ "this method");
}

Java Tutorials

Java Tutorial on this website:

https://www.testingdocs.com/java-tutorial/

For more information on Java, visit the official website :

https://www.oracle.com/java/

Exit mobile version