Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous Inner classes and Final modifier [duplicate]

Tags:

java

To my understand correctly anonymous classes are always final:

This has been mentioned specifically in JLS 15.9.5

However, when i run the following code to check that it is showing that Inner class is not final.

    public class Test{
    static class A<T> {
    }
    public static void main(String arg[]) {
        A<Integer> obj = new A() {
        };
        if ((obj.getClass().getModifiers() & Modifier.FINAL) != 0) {
            System.out.println("It is a final  " + obj.getClass().getModifiers());
        } else {
            System.out.println("It is not final " + obj.getClass().getModifiers());
        }
    }
}

Output of above program is :

It is not final 0

Please clear my doubt as i am not able to understand this behavior.

like image 714
Sachin Sachdeva Avatar asked Jun 29 '17 06:06

Sachin Sachdeva


People also ask

Which is true about anonymous inner class?

1. Which is true about an anonymous inner class? A. It can extend exactly one class and implement exactly one interface.

Can an anonymous inner class implement multiple interfaces?

A normal class can implement any number of interfaces but the anonymous inner class can implement only one interface at a time.

What is the difference between anonymous class and inner class?

A local inner class consists of a class declared within a method, whereas an anonymous class is declared when an instance is created. So the anonymous class is created on the fly or during program execution.

When Should anonymous inner classes be used?

In simple words, a class that has no name is known as an anonymous inner class in Java. It should be used if you have to override a method of class or interface. Java Anonymous inner class can be created in two ways: Class (may be abstract or concrete).


1 Answers

I agree this may be considered a bug, given that other cases in the JLS exhibit a different behavior. Case in point is an interface: As per section 9.1.1.1:

Every interface is implicitly abstract.

And when running the below:

interface X {
    void foo();
}

public static void main(String arg[]) {
    System.out.println(Modifier.isAbstract(X.class.getModifiers()));
}

It returns true.

Another example is an enum where the JLS specifies:

An enum declaration is implicitly final unless it contains at least one enum constant that has a class body

And the below example is perfectly aligned with it.

enum X {

}

public static void main(String arg[]) {
    System.out.println(Modifier.isFinal(X.class.getModifiers()));  // true
}
like image 75
M A Avatar answered Sep 27 '22 21:09

M A