What is final object in java

What is the point of «final class» in Java?

I am reading a book about Java and it says that you can declare the whole class as final . I cannot think of anything where I’d use this. I am just new to programming and I am wondering if programmers actually use this on their programs. If they do, when do they use it so I can understand it better and know when to use it. If Java is object oriented, and you declare a class final , doesn’t it stop the idea of class having the characteristics of objects?

25 Answers 25

First of all, I recommend this article: Java: When to create a final class

If they do, when do they use it so I can understand it better and know when to use it.

A final class is simply a class that can’t be extended.

(It does not mean that all references to objects of the class would act as if they were declared as final .)

When it’s useful to declare a class as final is covered in the answers of this question:

If Java is object oriented, and you declare a class final , doesn’t it stop the idea of class having the characteristics of objects?

By marking a class as final you disable a powerful and flexible feature of the language for that part of the code. Some classes however, should not (and in certain cases can not) be designed to take subclassing into account in a good way. In these cases it makes sense to mark the class as final, even though it limits OOP. (Remember however that a final class can still extend another non-final class.)

To add to the answer, one of the principles of Effective Java is to favor composition over inheritance. The use of the final keyword also helps to enforce that principle.

«You do it mainly for efficiency and security reasons.» I hear this remark quite often (even Wikipedia states this) but I still don’t understand the reasoning behind this argument. Does someone care to explain how, say, a non-final java.lang.String would have ended up either inefficient or insecure?

@MRA If I create a method that accepts a String as a parameter, I assume that it’s immutable, because Strings are. As a result of this, I know I can call any method on the String object safely, and not change the passed String. If I were to extend String, and change the implementation of substring to change the actual String, then the String object you expected to be immutable is no longer immutable.

@Cruncher Why not make substring final and leave String open for extension? This would be in keeping with the «Open-Closed Principle» mentioned in Sean Patrick Floyd’s post.

@Sortofabeginner And as soon as you say you want all String methods and fields to be final, just so that you can create some class with additional functionality. At that point you might as well just create a class that has-a string and create methods that operate on that string.

In Java, items with the final modifier cannot be changed!

This includes final classes, final variables, and final methods:

  • A final class cannot be extended by any other class
  • A final variable cannot be reassigned another value
  • A final method cannot be overridden
Читайте также:  Таблица с закругленными краями html

The statement, «In Java, items with the final modifier cannot be changed!», is too categorical and, in fact, not entirely correct. As Grady Booch put it, «An object has state, behavior, and identity». While we can’t change an object’s identity once its reference has been marked as final, we do have a chance to change its state by assigning new values to its non- final fields (provided, of course, it has them.) Anyone who is planning to obtain an Oracle Java Certification (such as 1Z0-808, etc.) should keep this in mind because there might be questions on this aspect on the exam.

One scenario where final is important, when you want to prevent inheritance of a class, for security reasons. This allows you to make sure that code you are running cannot be overridden by someone.

Another scenario is for optimization: I seem to remember that the Java compiler inlines some function calls from final classes. So, if you call a.x() and a is declared final , we know at compile-time what the code will be and can inline into the calling function. I have no idea whether this is actually done, but with final it is a possibility.

The inlining is normally only done by the just-in-time compiler at runtime. It works without final, too, but the JIT-compiler has a bit more work to do to be certain that there are no extending classes (or that these extending classes do not touch this method).

A good write up on the issue of inlining and optimization can be found here: lemire.me/blog/archives/2014/12/17/…

I think the term security is used in an almost confusing academic sense to mean safety. Safety meaning when you work with a class you know another class hasn’t extended it and is relying on the internal implementations of the base class. I think we’ve all been in situations where classes are extended in all sorts of nasty ways and it’s impossible to reason about the code without taking out a good chunk of your day.

which is an immutable class and cannot be extended. Of course, there is more than just making the class final to be immutable.

If you imagine the class hierarchy as a tree (as it is in Java), abstract classes can only be branches and final classes are those that can only be leafs. Classes that fall into neither of those categories can be both branches and leafs.

There’s no violation of OO principles here, final is simply providing a nice symmetry.

In practice you want to use final if you want your objects to be immutable or if you’re writing an API, to signal to the users of the API that the class is just not intended for extension.

Relevant reading: The Open-Closed Principle by Bob Martin.

Software Entities (Classes, Modules, Functions, etc.) should be open for Extension, but closed for Modification.

The final keyword is the means to enforce this in Java, whether it’s used on methods or on classes.

@Sean: Doesn’t declaring it final make the class closed for extension rather than open? Or am I taking it too literally?

@Goran globally applying final, yes. The key is to selectively apply final in places where you don’t want modification (and of course to provide good hooks for extension)

Читайте также:  Css опустить элемент вниз

In OCP, «modification» refers to modifying the source code, and «extension» refers to implementation inheritance. Therefore, use of final on a class/method declaration would not make sense if you want the implementation code to be closed for modification but open for extension by inheritance.

@Rogerio I have borrowed the reference (and the interpretation) from the Spring Framework Reference (MVC). IMHO this makes a lot more sense than the original version.

Extension is dead. Useless. Decimated. Destroyed. I don’t care about OCP. There’s never an excuse to extend a class.

The keyword final itself means something is final and is not supposed to be modified in any way. If a class if marked final then it can not be extended or sub-classed. But the question is why do we mark a class final ? IMO there are various reasons:

  1. Standardization: Some classes perform standard functions and they are not meant to be modified e.g. classes performing various functions related to string manipulations or mathematical functions etc.
  2. Security reasons: Sometimes we write classes which perform various authentication and password related functions and we do not want them to be altered by anyone else.

I have heard that marking class final improves efficiency but frankly I could not find this argument to carry much weight.

If Java is object oriented, and you declare a class final, doesn’t it stop the idea of class having the characteristics of objects?

Perhaps yes, but sometimes that is the intended purpose. Sometimes we do that to achieve bigger benefits of security etc. by sacrificing the ability of this class to be extended. But a final class can still extend one class if it needs to.

On a side note we should prefer composition over inheritance and final keyword actually helps in enforcing this principle.

final class can avoid breaking the public API when you add new methods

Suppose that on version 1 of your Base class you do:

class Derived extends Base < public int method() < return 1; >> 

Then if in version 2 you want to add a method method to Base :

it would break the client code.

If we had used final class Base instead, the client wouldn’t have been able to inherit, and the method addition wouldn’t break the API.

A final class is a class that can’t be extended. Also methods could be declared as final to indicate that cannot be overridden by subclasses.

Preventing the class from being subclassed could be particularly useful if you write APIs or libraries and want to avoid being extended to alter base behaviour.

In java final keyword uses for below occasions.

In java final variables can’t reassign, final classes can’t extends and final methods can’t override.

Be careful when you make a class «final». Because if you want to write an unit test for a final class, you cannot subclass this final class in order to use the dependency-breaking technique «Subclass and Override Method» described in Michael C. Feathers’ book «Working Effectively with Legacy Code». In this book, Feathers said, «Seriously, it is easy to believe that sealed and final are a wrong-headed mistake, that they should never have been added to programming languages. But the real fault lies with us. When we depend directly on libraries that are out of our control, we are just asking for trouble.»

Читайте также:  Oracle php на сервере

That is a technique of legacy code, not a technique for a new class you are writing, which is by definition not legacy code.

If the class is marked final , it means that the class’ structure can’t be modified by anything external. Where this is the most visible is when you’re doing traditional polymorphic inheritance, basically class B extends A just won’t work. It’s basically a way to protect some parts of your code (to extent).

To clarify, marking class final doesn’t mark its fields as final and as such doesn’t protect the object properties but the actual class structure instead.

What does the object properties mean? Does it mean I could modify the member variable of the class if the class is declared final? So the only purpose of final class is to prevent inheritance.

TO ADDRESS THE FINAL CLASS PROBLEM:

There are two ways to make a class final. The first is to use the keyword final in the class declaration:

public final class SomeClass < // . . . Class contents >

The second way to make a class final is to declare all of its constructors as private:

Marking it final saves you the trouble if finding out that it is actual a final, to demonstrate look at this Test class. looks public at first glance.

Unfortunately, since the only constructor of the class is private, it is impossible to extend this class. In the case of the Test class, there is no reason that the class should be final. The Test class is a good example of how implicit final classes can cause problems.

So you should mark it final when you implicitly make a class final by making it’s constructor private.

One advantage of keeping a class as final :-

String class is kept final so that no one can override its methods and change the functionality. e.g no one can change functionality of length() method. It will always return length of a string.

Developer of this class wanted no one to change functionality of this class, so he kept it as final.

The other answers have focused on what final class tells the compiler: do not allow another class to declare it extends this class, and why that is desirable.

But the compiler is not the only reader of the phrase final class . Every programmer who reads the source code also reads that. It can aid rapid program comprehension.

In general, if a programmer sees Thing thing = that.someMethod(. ); and the programmer wants to understand the subsequent behaviour of the object accessed through the thing object-reference, the programmer must consider the Thing class hierarchy: potentially many types, scattered over many packages. But if the programmer knows, or reads, final class Thing , they instantly know that they do not need to search for and study so many Java files, because there are no derived classes: they need study only Thing.java and, perhaps, it’s base classes.

Источник

Оцените статью