3

When we declare all variables and methods in a class as final, we are restricted the concept of override.

Then, "what is the reason we want to restrict IS-A relationship in an OOP language( even we restrict IS-A relationship, this language has Has-A relationship) by using final class?"

My point is we can not restrict the accessing the members of our class any way, then give an easy access by allowing IS-A relationship. Otherwise it is a headache to create objects and all? (in my view 'access' not includes modifications)

If I miss any important theme of programming , please excuse me. And tell me, what is it?

3 Answers3

1

Is there any necessity to declare a class as final class?

Necessity, no. Declare a class final if you want to forbid extending it. This can prevent programming errors. For example it's a recommended practice to make utility classes with only static methods to be final, as inheriting from such class wouldn't make sense, and be clearly a programming error.

janos
  • 120,954
  • 29
  • 226
  • 236
1

Security would be one necessity. String class in Java is an Immutable/final class. No sub-classing is possible System class is another example.

Have more read here: Good reasons to prohibit inheritance in Java?

Community
  • 1
  • 1
Pavan Dittakavi
  • 3,013
  • 5
  • 27
  • 47
0

Is there any necessity to declare a class as final class?

Yes. If you are implementing a Singleton pattern with a class. If someone can sub-class your Singleton, then there may be more than one (which violates the Singleton pattern).

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249