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

60 Views Asked by At
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?

2

There are 2 best solutions below

3
Joachim Sauer On BEST ANSWER

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.

0
Mureinik On

human has a compile time type of Human, so when using that reference you act access members (be it data members or methods) that aren't defined by the Human class.

The fact that you're using an anonymous class is inconsequential - the same compiler errors would occur if you extended Human with a named class:

public class SpecialHuman extends Human {
    int x = 10;

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

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

    public static void main(String[] args) {
        Human h = new SpecialHuman();
        human.eat();
        human.x = 10;   //Illegal
        human.test();   //Illegal
}