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.

Java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

classTest

{

publicstaticvoiddisplay()

{

System.out.println("From Test");

}

}

publicclassDemoextendsTest

{

publicstaticvoiddisplay()

{

System.out.println("From Demo");

}

publicstaticvoidmain(Stringargs[])

{

display();

}

}

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.

Java

1

2

3

4

5

publicstaticvoiddisplay()

{

super.display();// cause of error

System.out.println("From Demo");

}

Following is the screenshot of error message.

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

Java

1

2

3

4

5

6

7

8

9

10

11

12

publicclassDemoextendsTest

{

@Override

publicstaticvoiddisplay()

{

System.out.println("From Demo");

}

publicstaticvoidmain(Stringargs[])

{

display();

}

}

Following is the screenshot of error message.

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.

As static methods cannot be inherited, no question of overriding.

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.

Static methods are part of class but not part of object. As a part static methods can be overloaded but cannot be overridden.

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.