Mohammad Ali Asgar
Mohammad Ali Asgar

Reputation: 734

A final class and underlying consequences in Java

I heard this line somewhere and I cannot get it off of my mind:

"All members of a final class are implicitly final."

Now, I know very well these three famous concepts:

  1. A final class cannot be extended.
  2. A final variable cannot be re-assigned with a new value once initialized.
  3. A final method cannot be overridden.

But, if all members (variables, methods) of a final class are implicitly final, then we have a final class AND final variables AND final methods in it.

Then, how is it possible that StringBuilder, despite being final, allows its contents to change?!

Upvotes: 0

Views: 130

Answers (2)

Darkhogg
Darkhogg

Reputation: 14175

That assertion is oversimplified and therefore wrong. Only methods of a final class can be considered implicitly final. This fact is however irrelevant in itslef, as methods of a final class cannot be overriden because there can't be any subclasses. It doesn't really matter if they're final or not, implicitly or explicitly.

Upvotes: 2

Bohemian
Bohemian

Reputation: 425278

A class can be final, but mutable.

The class being final just means there can be no subclasses, but says nothing about the behaviour of the class.

Conversely, fields and methods can be final (and the instances immutable), but the class not final.

Finality of a class and of class members are unrelated.

Upvotes: 1

Related Questions