javaobjectmethodsanonymous-classanonymous-inner-class

Declaring a method when creating an object


Why first way is correct, but second isn't?


First way:

new Object() {
    public void a() {
        /*code*/
    }
}.a();

Second way:

Object object = new Object() {
    public void a() {
        /*code*/
    }
};

object.a();

And where can I find more information about it?


Solution

  • java.lang.Object has no a methods declared (2), while the anonymous class returned by the class instance creation expression new Object() { public void a() {} } does (1).

    Use Java 10's local variable type inference (var) to make the second option as valid as the first one.

    var object = new Object() {
        public void a() {}
    };
    object.a();