To my understanding, the following code should have printed true
.
However, when I ran this code it is printing false
.
From Java docs of Anonymous Classes 15.9.5. :
An anonymous class is always implicitly final
public class Test {
public static void main(String args[]) {
Object o = new Object() {
};
System.out.println("Annonymous class is final: " + Modifier.isFinal(o.getClass().getModifiers()));
}
}
Can some one please help me understand this behavior.
I didn't know the reasoning behind this, but, according to @Hulk's answer and this bug report, it seems the specification of previous versions slightly misled us saying that anonymous classes are final.
Anonymous classes are considered implicitly
final
since you can't create sub-classes of them. That doesn't mean that theModifier.FINAL
modifier should be set for anonymous classes.Note that the wording in the JLS of that particular section has changed significantly since then. It now (JLS 11) reads:
15.9.5. Anonymous Class Declarations:
This change in wording was introduced in JLS 9. The semantics of anonymous classes and the behavior of the methods in the question remained unchanged, the intention was to avoid exactly the kind of confusion this question is about.
The ticket that caused the change says:
See Javadoc of
Class.getModifiers()
: https://docs.oracle.com/javase/10/docs/api/java/lang/Class.html#getModifiers()It says "...The values of its other modifiers are not determined by this specification".