Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why avoid the final keyword?

In java, is there ever a case for allowing a non-abstract class to be extended?

It always seems to indicate bad code when there are class hierarchies. Do you agree, and why/ why not?

like image 491
Snukker Avatar asked Feb 06 '09 11:02

Snukker


People also ask

Why do we need final keyword?

In Java, the final keyword can be used while declaring an entity. Using the final keyword means that the value can't be modified in the future. This entity can be - but is not limited to - a variable, a class or a method.

Does final keyword increase performance?

When we apply the final keyword to a class, then that class cannot be subclassed. When we apply it to a method, then that method cannot be overridden. There are no reported performance benefits of applying final to classes and methods.

When you use final keyword for a method you Cannot?

2) final method A final method cannot be overridden.

What happens if a method has the final keyword as modifier?

If we initialize a variable with the final keyword, then we cannot modify its value. If we declare a method as final, then it cannot be overridden by any subclasses.


1 Answers

there a good reasons to keep your code non-final. many frameworks such as hibernate, spring, guice depend sometimes on non-final classes that they extends dynamically at runtime.

for example, hibernate uses proxies for lazy association fetching. especially when it comes to AOP, you will want your classes non-final, so that the interceptors can attach to it. see also the question at SO

like image 140
Andreas Petersson Avatar answered Sep 21 '22 08:09

Andreas Petersson