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.
1. Which is true about an anonymous inner class? A. It can extend exactly one class and implement exactly one interface.
A normal class can implement any number of interfaces but the anonymous inner class can implement only one interface at a time.
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.
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).
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
}
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