我试图理解在Java中使用匿名类。基本上我已经在方法中创建了一个匿名类,即testAnonymous,那么如何将匿名类作为字段添加到其父类MyClass?
我的代码肯定存在问题。我也在下面评论过。希望有助于解释这个问题。我无法理解这一点。谢谢你的帮助!
public class MyClass {
private int number;
private String name;
private Greeting greeting; //the anonymous class FrenchGreeting extends Greeting
// so is this the way to add the instance of anonymous class?
...
public void sayHi(){
Greeting frenchGreeting= new Greeting(){ //created an anonymous class
//override some method in Greeting, to make it a french greeting
}
frenchGreeting.greet();//why can't I use the method in Greeting class here?
}