Ertuğrul Çetin
Ertuğrul Çetin

Reputation: 5231

What is the purpose of declaring final methods in final classes in Java

I was reading LinkedHashMap source code and i came across with inner final class LinkedKeyIterator.Also i have seen lots of same code in java's source code.

Which is like that:

  final class LinkedKeyIterator extends LinkedHashIterator
        implements Iterator<K> {
        public final K next() { return nextNode().getKey(); }
    }

We know that final classes cant be extended so we can not override methods.

Why next method declared as final?

Upvotes: 4

Views: 600

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074335

It's purely documentation/emphasis, per JLS§8.4.3.3:

A private method and all methods declared immediately within a final class (§8.1.1.2) behave as if they are final, since it is impossible to override them.

As Pshemo said in a comment, whether the method was declared final can be determined via reflection, and the compiler won't automatically add that to the signature. So making methods explicitly final improves documentation right down to the reflection level.

Upvotes: 4

Related Questions