In this artcile we will discuss how to prevent method overriding in Java.

By preventing method overriding in Base class, we means that any class that extends this Base class will not able to override these methods.  Need of preventing method overriding is dicussed in next article.

Preventing Method Overriding in Java

Method overriding works because of Run-time method Binding feature in Java. So, if we force the java compiler to do static binding for a method then we can prevent that method from being overridden in Derived class.

We can prevent method overriding in java in 3 ways i.e.

  1. By making method final in Base class
  2. By making method static in Base class
  3. By making method private in Base class

Let’s discus them one by one i.e.

Final methods can not be overridden

By making a method final we are adding a restriction that Derived class can not override this particular method i.e. checkout following example,

Output:

Here Derived class can override fun() method because that non final in Base class but it cannot override test() method because that’s final in Base class.

Static methods can not be overridden in Java

We can not override the static methods in Derived class because Static function are linked with Class not with object. It means when we call a static method then JVM does not pass the this reference to it, like it does for all non static methods. So, static method doesn’t have a this reference avialable. Therefore run-time binding cannot take place for static methods. For static methods in Java, static binding takes place. Hence we can not override static methods in Java. Checkout this example,

Output:

Private methods can not be overridden

Private methods of Base class are not visible in Derived class, hence they can not be override. Checkout following example,

Output:

 

Click Here to Subscribe for more Articles / Tutorials like this.