Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

final static methods exam

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)

like image 594
Toby L Welch-Richards Avatar asked Dec 11 '12 16:12

Toby L Welch-Richards


3 Answers

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.

like image 122
Andrew Logvinov Avatar answered Nov 16 '22 20:11

Andrew Logvinov


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.

like image 45
OldCurmudgeon Avatar answered Nov 16 '22 18:11

OldCurmudgeon


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.

like image 41
irreputable Avatar answered Nov 16 '22 20:11

irreputable