2

Java don't let static method of a class to get overridden. So If a Super class method is static, in Sub Class same name method also needs to be static with same signature in order to compile, though it not a method overriding. Below is an example:

enter image description here

But my question is, so if this is not method overriding, then why can't I make the static method in Super Class final?

enter image description here

Bitan Biswas
  • 51
  • 1
  • 8
  • because you have already declared the foo() method of your super class as "final" that is what "final" keyword is supposed to do. – Shubham Nov 12 '18 at 07:02
  • 6
    [Don't post images of code.](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-on-so-when-asking-a-question) – shmosel Nov 12 '18 at 07:04
  • The duplicate is not relevant to the question, since the OP already knows static methods can't be overridden and is not asking about that (he's asking why the final modifier in the super-class static method prevents a sub-class from defining a static method with same signature, which is not overriding). I'm voting to re-open. – Eran Nov 12 '18 at 07:09

1 Answers1

4

If you look at JLS 8.4.3.3 final Methods, you'll see that the final method modifier prevents methods from either being overridden or hidden.

A method can be declared final to prevent subclasses from overriding or hiding it.

It is a compile-time error to attempt to override or hide a final method.

A static method cannot be overridden, but it can be hidden. The final modifier prevents it from being hidden by a sub-class static method.

Community
  • 1
  • 1
Eran
  • 387,369
  • 54
  • 702
  • 768
  • Thanks @Eran for correctly getting to the point I wanted to make and your answer helped me to understand method hiding very precisely. – Bitan Biswas Nov 12 '18 at 07:28
  • Hi, I am also trying to understand that in which case we use static final both as both can't be override ... what do we mean by hidden here? as the function is public how it can be hidden – Shubham Jain Feb 04 '20 at 02:18