I have been studying for my Software Development course and came across the question from a sample:
"Why does it make no sense to have both the static and final modifiers in front of a Java method?"
I have had a bit of a research and everywhere I go it says it is not bad practice and there are good reasons for doing so - for example, this stackoverflow question: Is it a bad idea to declare a final static method?
So, is this question itself nonsensical or is there a legitimate answer to this question?
(There are no given solutions to this sample paper)
static
methods cannot be overriden since they're associated not with an instance of class, but with the class itself. For example, this is how you'd usually call static
method:
MyClass.myStaticMethod()
And this is how you call an instance method:
new MyClass().myInstanceMethod()
final
modifier is used with methods to disallow their override in extending classes.
Because a static
method cannot be overridden. There is therefore no point in marking it final
.
Note however that static final
variables (which are, oddly, therefore NOT variables because they cannot change) are very useful because their values can be inlined by the compiler.
Static methods can be sort of overridden (though that's not the technical term), since it is resolved at runtime, searching upwards in class chain until it's found. But this "feature" is probably a mistake; people don't use it, people don't know about it, we should pretend it doesn't exist.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With