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?
The type
Humandoes not have either a fieldxor a methodtest()and your variablehumanis 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
Humanwith that nonexistent name.However, if you use
varthen the local variable type inference will give the variable the type of that anonymous class, so replacingHuman human = ...withvar human =will make your code compile.