2

I was asked about the reason of why a final class cannot be overridden. I tried to explain that it is more of design approach where by you don't want your class to be extended or methods to be overridden and a final class also helps to make an object immutable (though there are more steps to be done rather than just declaring the class as final).

However I would like to know if there is more to thought process behind declaring a class as final or the fact that it cannot be overridden?

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
user3137375
  • 113
  • 1
  • 5

4 Answers4

1

Because them's the rules; It's a part of the design of the language.

http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.1.1.2

As a designer you say "my class is not suitable for inheritence"; Java honours this by explicitly preventing someone from doing so.

0

final methods can't be overriden, because that's what final is designed to do: it's a sign saying "do not override this".

From Wiki

A final method cannot be overridden or hidden by subclasses. This is used to prevent unexpected behavior from a subclass altering a method that may be crucial to the function or consistency of the class.

A common misconception is that declaring a class or method as final improves efficiency by allowing the compiler to directly insert the method wherever it is called (see inline expansion). But because the method is loaded at runtime, compilers are unable to do this. Only the runtime environment and JIT compiler know exactly which classes have been loaded, and so only they are able to make decisions about when to inline, whether or not the method is final.

Community
  • 1
  • 1
Rakesh KR
  • 6,357
  • 5
  • 40
  • 55
0

Final class cannot be extended because Java compiler will not allow it, because Java compiler follows the rules defined by Java Language Specification which does not allow it.

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
0

A final class is a class that can't be extended, thats the reason u cannot override the final class

it is also used to make the class immutable

and one good advantage of defining class as final that it improves JVM performance see this

Community
  • 1
  • 1
Girish
  • 1,717
  • 1
  • 18
  • 30