Java - Inner Anonymous Class

Subscribe Send me a message home page tags


Anonymous class in Java is a kind of syntax sugar. It may improve productivity but on the other hand we need to be careful about we are doing.

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 -----

Welcome to join reddit self-learning community.
Send me a message Subscribe to blog updates

Want some fun stuff?

/static/shopping_demo.png