Search code examples
javaclassoopcompiler-errorsanonymous-class

Why are human.x=10 and human.test(0) compile error in Java with anonymous inner class?


class Human {

    void eat() {
        System.out.println("human eat!");
    }
}

public class Demo {

    public static void main(String[] args) {
        Human human = new Human() {
            int x = 10;

            public void test() {
                System.out.println("test - anonymous");
            }

            @Override
            void eat() {
                System.out.println("customer eat!");
            }

        };

        human.eat();
        human.x = 10;   //Illegal
        human.test();   //Illegal
    }
}

In this code why are human.x=10; and human.test(0); compile errors?


Solution

  • The type Human does not have either a field x or a method test() and your variable human is defined as that type.

    Your anonymous inner class has that field and that method, so you'd need to define the variable as that type. But "anonymous" means it doesn't have a name, so you can't just replace Human with that nonexistent name.

    However, if you use var then the local variable type inference will give the variable the type of that anonymous class, so replacing Human human = ... with var human = will make your code compile.