Where is the final class used in Java?

Asked 1 years ago, Updated 1 years ago, 106 views

I read a book about Java. It said that all classes can be declared final. But I don't know where to use the final class.

I just learned this new method, so I wonder if programmers actually apply it to programs. If you apply it, it would be more helpful for me to understand if I know when to use it. And I think I'll know when to use it.

If the class is object-oriented even if you define it as final, please explain why.

java final

2022-09-22 22:30

1 Answers

First of all, you said you were curious about how to use it. You can think of the final class as simply a class that cannot be expanded. This is different from simply declaring the value of an object as final. If you look at the book called Effective Java, it says this.

In general classes, inheritance is usually carried out, so it is neither final nor designed or documented for inheritance. However, this behavior is dangerous. Whenever such a class changes, there is a possibility that the client's subclass will not work properly. This is not just a matter of theory. It is by no means uncommon for a company-related defect to be reported after the final, which is not designed or documented for inheritance, modifies the internal code of the entity class. The best way to solve this problem is to prohibit inheritance of undesigned or documented classes so that subclasses can be made safe. There are two ways to prevent inheritance. The easier of the two is to declare the class final. The next best option is to dedicate all constructors to private or package use, and add a public static factory method instead of a constructor. This method provides flexibility when using subclasses."

If you haven't considered inheritance enough as mentioned above, you may experience unexpected things between the parent class and the inheritance class. So classes can be classified into two categories.

It's not a big deal to write a few more characters in a class if you're going to write a code that's thousands of lines. If you put meaning into just making the code right away without maintenance, you won't need final but you just need to know that the final easily tells you that this class is designed without inheritance in mind.


2022-09-22 22:30

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.