The caveat of the anonymous class is that it is usually an inner class in the first place. There are two types of inner class: (1)
static
inner class and (2) non-static inner class. The difference between these two types is that the non-static inner class has reference to the enclosing class. Therefore, it takes extra space. When using an anonymous, we cannot explicitly use the keyword
static
. Whether or not this anonymous class is static depends on the context. If it is defined/used in a static method, the anonymous class is static; if it is defined/used in a non-static method, then the anonymous class is non-static.
Here is the demo code:
class MyClass {
public int value;
public MyClass(int value ) {
this.value = value;
}
public void printValue() {
System.out.println("MyClass has value " + value);
}
}
public class InnerClassDemo {
private static int staticValue = -100;
private int nonStaticValue;
public InnerClassDemo(int value) {
nonStaticValue = value;
}
public MyClass getFromInstanceMethod() {
return new MyClass (10) {
@Override
public void printValue() {
System.out.println("[getFromInstanceMethod] value = " + value + ", nonStaticValue = " + nonStaticValue);
}
};
}
public static MyClass getFromStaticMethod() {
return new MyClass(20) {
@Override
public void printValue() {
System.out.println("[getFromStaticMethod] value = " + value + ", staticValue = " + staticValue );
}
};
}
public static void main(String[] args) {
InnerClassDemo instance = new InnerClassDemo(100);
instance.getFromInstanceMethod().printValue();
instance.getFromStaticMethod().printValue();
}
}
And the output of the program is:
[getFromInstanceMethod] value = 10, nonStaticValue = 100 [getFromStaticMethod] value = 20, staticValue = -100
----- END -----
©2019 - 2022 all rights reserved