newbie newbie - 6 months ago 9
Java Question

Use 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?

Answer

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.

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