Can we override static method in Java with Example?

Can we override static method in Java with Example?


The super class static methods cannot be overridden by sub class because they do not represent the state of the object or with static methods no encapsulation exists. For this reason, the super class static methods are not part of subclass. When they are not part of subclass, they cannot be overridden.

Let us write a simple example to prove that we cannot override static method.

override static method

The above code compiles, executes and prints "From Demo". It looks, the static display() method of Test is overridden by subclass Demo as both are identical. No, both methods are treated distinct from each other. That is, subclass display() is no way connected with super class display() method.

Both are treated separate and does not know each other. We cannot override static method. How to prove it? There are two ways.

1. Using super.display(): We know in method overriding, the super class method is hidden by subclass method. To call super class method from subclass method, we use super keyword as follows. Calling super now shows error as subclass display() is not a overridden method.

Following is the screenshot of error message.

override static method

2. Using @Overfide: Use @Override annotation introduced with JDK 1.5.

Following is the screenshot of error message.

override static method

The annotation @Override means that there is an equivalent method in super class which is overridden. The error message is shown as subclass display() is distinct from super class one.

Let us think more with the following points on static overriding.

  1. As static methods cannot be inherited, no question of overriding.
  2. Static methods are treated as class methods (like static variables are known as class variables) or class level methods. So, they cannot be inherited and overridden.
  3. Static methods are part of class but not part of object. As a part static methods can be overloaded but cannot be overridden.
  4. Overridden methods support dynamic binding and which method is to be dispatched for execution is decided at runtime. As static methods are binded at compile time (known as static binding), they cannot support dynamic binding.

Leave a Reply

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