What is the point of "final class" in Java?

525,246

Solution 1

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?

In some sense yes.

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.)

Solution 2

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

Solution 3

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.

Solution 4

The best example is

public final class String

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

Solution 5

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.

Share:
525,246
newbie
Author by

newbie

I'm a newbie, a novice, an amateur, a beginner in programming. My Total Programming Experience is approximately equal to the no. of months I joined here! So pardon me for my idiotic questions. My dream is to be a great programmer someday. To make the impossible, possible. I want to be the female version of Mr. Jon Skeet and my idol (who always scolds me hehehe) Mr Balusc. But I think, based on my current capabilities, i need a whooping 50 years to be on their level. So help me God! BTW, i really find this site super cool! I could interact and learn from many great programmers around the world. And for a programmer-wannabe like me, every opinion matters. What's important is that I'm learning a lot here which I could not learn by just reading books. So thank you everyone for all the help. I think I am becoming a stackoverflow addict.

Updated on July 08, 2022

Comments

  • newbie
    newbie almost 2 years

    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?

  • Zoidberg
    Zoidberg over 13 years
    Hehe, sometimes it protects Rube Goldergian developers from themselves.
  • Riggy
    Riggy over 13 years
    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.
  • Goran Jovic
    Goran Jovic over 13 years
    @Sean: Doesn't declaring it final make the class closed for extension rather than open? Or am I taking it too literally?
  • Sean Patrick Floyd
    Sean Patrick Floyd over 13 years
    @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)
  • Paŭlo Ebermann
    Paŭlo Ebermann over 13 years
    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).
  • Rogério
    Rogério over 13 years
    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.
  • Sean Patrick Floyd
    Sean Patrick Floyd over 13 years
    @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.
  • MRA
    MRA almost 12 years
    "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?
  • Cruncher
    Cruncher almost 11 years
    @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.
  • Brian McCutchon
    Brian McCutchon about 10 years
    @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.
  • Cruncher
    Cruncher about 10 years
    @Sortofabeginner because it's not just substring. String as a CONTRACT is entirely immutable. As soon as you extend it is no longer a guarantee. When you have something like this so entrenched into a language, it's best to just not let people change that...
  • Cruncher
    Cruncher about 10 years
    @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.
  • Celeritas
    Celeritas almost 10 years
    @Shay final (amongst other things) is used to make an object immutable, so I wouldn't say they have nothing to do with each other. See here docs.oracle.com/javase/tutorial/essential/concurrency/…
  • Josh Hemann
    Josh Hemann over 9 years
    A good write up on the issue of inlining and optimization can be found here: lemire.me/blog/archives/2014/12/17/…
  • spongebob
    spongebob almost 9 years
    The actual question is why, not what.
  • Igor Soudakevitch
    Igor Soudakevitch about 8 years
    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...
  • Adam Lyu
    Adam Lyu almost 8 years
    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.
  • Josh Woodcock
    Josh Woodcock over 6 years
    Extension is dead. Useless. Decimated. Destroyed. I don't care about OCP. There's never an excuse to extend a class.
  • Karan Khanna
    Karan Khanna over 6 years
    It's to enforce that a class cannot be extended.
  • Sean Patrick Floyd
    Sean Patrick Floyd over 6 years
    @KaranKhanna obviously, yes. But the reason to do that is the Open/Closed Principle.
  • Karan Khanna
    Karan Khanna over 6 years
    @SeanPatrickFloyd with final we are making the class closed for extension also and leaving no scope of improvements. A class should only be declared final when we are sure that no improvements will be required.
  • Sean Patrick Floyd
    Sean Patrick Floyd over 6 years
    @KaranKhanna a) this question was not only about final on class level. Making methods final can be a clear guidance on how a class is supposed to be extended. b) The OCP can apply to an entire codebase. We can prohibit the extension of specific classes (e.g. java.lang.Integer) and still provide an extendable API (java.lang.Number). And no, I disagree: Effective Java Item 17 says "Design and document for inheritance or else prohibit it". Final classes should be the default. One of the many cases where Java sets defaults badly.
  • WackGet
    WackGet almost 4 years
    This answer relies on an external source to provide details. You should edit the answer and include the details in case the external URL ever goes down.
  • premek.v
    premek.v over 3 years
    > cannot be overridden by someone By who?
  • Anther
    Anther over 3 years
    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.
  • Jacob van Lingen
    Jacob van Lingen over 3 years
    "Some classes however, should not be designed to take subclassing into account in a good way.". A nice example would be the utility class, see Lomboks @UtilityClass for a nice implementation.
  • Raedwald
    Raedwald almost 3 years
    That is a technique of legacy code, not a technique for a new class you are writing, which is by definition not legacy code.