Why should we prevent Method Overriding in Java

In the previous article we discussed, how to prevent method overriding in Java. In this article we will discuss what’s the need of Preventing method overriding in Java.

Need of preventing Method Overriding in Java

We generally prevent method overriding in Base class because of two reasons i.e.

  1. Design Decision
  2. Performance

Lets discuss both of them in detail i.e.

Design Decision

Many times we want to retain behavior of a method i.e. Derived class should not modify the behavior which Base class has provided for a particular method. For example,

We can Create a new class by extending from Thread class and override its run() method. Thread class will execute our Derived class’s run() method in parallel thread.

But Thread class has restricted the Overriding of some other methods like setPriority() & setName() etcby making it final i.e.

// In Thread class
public final void setPriority(int newPriority){..}
public final synchronized void setName(String name) {..}
class SampleThread extends Thread
{
	@Override
	public void run() {
		System.out.println("Derived class Test.run()");
	}
	
	/*
	// Can not Override the setPriority
	
	public void setPriority(int newPriority) {
     super.setPriority(newPriority);
    }
    */
}

Class that extends from Thread class, can not override these restricted methods like setPriority(), because that can hamper the functionality of Thread class. It was a Design decision that which method from Thread class can be overridden or not.

Performance

By default all public and protected methods in a class in Java are subject to Run-time Binding & method overriding. So, by preventing the method from being overridden, we are actually preventing the run-time binding of that method.

Method overriding works because of Run-time binding in java i.e. whenever we call a method from the reference variable, at run-time JVM will search and called the appropriate method based on the actual object pointed by reference. This lookup at run-time takes time as compare to Static Binding, because in Static binding compiler binds the function call with appropriate method. For method with static bind JVM need not to perform any extra stuff at run-time.

So, sometimes to improve performance we prevent the functions from being overridden.

 

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top