Thursday, 14 July 2022

What is the behaviour of static final method in Java?

Method hiding

If a subclass defines a class method (static method) with the same signature as a class method in the super class, the method in the subclass hides the one in the super class.

 

MethodHidingDemo.java

Animal.java

class Animal {
	static void printMsg() {
		System.out.println("I am the super class static method");
	}

	void showMsg() {
		System.out.println("I am the super class instance method");
	}
}

 

Tiger.java

public class Tiger extends Animal {
	static void printMsg() {
		System.out.println("I am the sub class static method");
	}

	void showMsg() {
		System.out.println("I am the sub class instance method");
	}

	public static void main(String args[]) {
		Animal ref = new Tiger();
		ref.printMsg();
		ref.showMsg();
	}
}

 

Output

I am the super class static method
I am the sub class instance method

 

As you observe the output, run time polymorphism not happened for the static method. So the message “I am the super class static method” printed.

 

The showMsg() method of class Tiger overrides the showMsg() of super class. Whereas, the printMsg() of subclass hides the printMsg() of super class.

 

 

How to disable method hiding?

The keyword final will disable the method from being hidden. When you attempt to hide a static final method in subclass, it will result in compiler error.

 


Update Animal class with static final method.

 

Animal.java

 

class Animal {
	static final void printMsg() {
		System.out.println("I am the super class static method");
	}

	void showMsg() {
		System.out.println("I am the super class instance method");
	}
}

 

When you try to compile Tiger class, you will get below compiler error.

bash-3.2$ javac Tiger.java 
Tiger.java:2: error: printMsg() in Tiger cannot override printMsg() in Animal
	static void printMsg() {
	            ^
  overridden method is static,final
1 error

Do not get confused with the error message, where it is talking about method overriding, ideally it is hiding (Overriding is applicable to instance methods, not for the static methods). I would recommend to read this post for more details.

 

References

Method hiding

  

You may like

Interview Questions

Can an enum has abstract methods in Java?

Can enum implement an interface in Java?

What happen to the threads when main method complete execution

Why System.out.println() is not throwing NullPointerException on null references?

Why should we restrict direct access to instance properties?

Closeable vs AutoCloseable in Java

No comments:

Post a Comment