Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does adding the 'final' keyword to methods in anonymous classes have any effect?

Tags:

java

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?

like image 217
Craig Otis Avatar asked Jun 03 '16 18:06

Craig Otis


1 Answers

The Java specification about final methods says:

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.

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.

like image 54
Tunaki Avatar answered Oct 29 '22 09:10

Tunaki