Note: I'm not asking the age-old question about why outer variables accessed in an anonymous class need to be declared final.
When creating an anonymous class in Java, you can add additional methods if you desire:
Runnable r = new Runnable() {
public void run() {
internal();
}
public void internal() {
.. code ..
}
};
However, Java also allows you to declare the additional methods as final
:
public final void internal() { ... }
My question is: Aren't those methods already effectively final, and does adding the final
keyword have any effect?
The Java specification about final
methods says:
A
private
method and all methods declared immediately within afinal
class (§8.1.1.2) behave as if they arefinal
, since it is impossible to override them.
and from Anonymous Class Declarations:
An anonymous class is always implicitly
final
(§8.1.1.2).
Therefore, an anonymous class is already final
, which makes all of its methods final
. You can add the final
modifier but it is redundant.
An interesting comment by Sotirios Delimanolis shows that the Reflection API actually won't report the final
modifier for an anonymous class:
public class Main {
public static void main(String[] args) {
Main anon = new Main() {};
System.out.println(Modifier.isFinal(anon.getClass().getModifiers())); // prints false
}
}
This is apparently a known bug (JDK-8129576) which is scheduled to be fixed in Java 9.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With