我正在浏览oracle文档中的匿名类教程(https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html)
我已经复制了本教程中使用的代码.(注释Statement1和Statement2由我添加):
public class HelloWorldAnonymousClasses { interface HelloWorld { public void greet(); public void greetSomeone(String someone); } public void sayHello() { class EnglishGreeting implements HelloWorld { String name = "world"; public void greet() { greetSomeone("world"); } public void greetSomeone(String someone) { name = someone; System.out.println("Hello " + name); } } HelloWorld englishGreeting = new EnglishGreeting(); HelloWorld frenchGreeting = new HelloWorld() { String name = "tout le monde"; //Statement1 public void greet() { greetSomeone("tout le monde"); } public void greetSomeone(String someone) { name = someone; System.out.println("Salut " + name); } }; HelloWorld spanishGreeting = new HelloWorld() { String name = "mundo"; //Statement2 public void greet() { greetSomeone("mundo"); } public void greetSomeone(String someone) { name = someone; System.out.println("Hola, " + name); } }; englishGreeting.greet(); frenchGreeting.greetSomeone("Fred"); spanishGreeting.greet(); } public static void main(String[] args) { HelloWorldAnonymousClasses myApp = new HelloWorldAnonymousClasses(); myApp.sayHello(); } }
本教程继续解释:匿名类表达式包含以下内容:
新的运营商
要实现的接口的名称或要扩展的类.在此示例中,匿名类正在实现接口HelloWorld.
括号,包含构造函数的参数,就像普通的类实例创建表达式一样.注意:实现接口时,没有构造函数,因此您使用一对空括号,如本例所示.
身体,是一个类声明体.更具体地说,在正文中,方法声明是允许的,但语句不是.
我对此没有感到困惑.4以上.它说匿名类声明体中不允许声明,但我可以看到它内部使用的语句.(我已经发表评论Statement1和Statement2来突出它们).
你可以解释一下教程想要从点号来传达的内容.4?
提前致谢.
不允许声明意味着不允许以下任何一种情况.
赋值表达式(aValue = 8933.234;
)
任何使用++或 - (aValue++;
)
方法调用(System.out.println("Hello World!");
)
对象创建表达式(Bicycle myBike = new Bicycle();
)
但是这份文件也说,
请注意,您可以在匿名类中声明以下内容:
字段
额外的方法(即使他们没有实现超类型的任何方法)
实例初始化器
本地课程
HelloWorld spanishGreeting = new HelloWorld() { String name = "mundo"; //Statement2 double aValue = 0.0; String s = "Hi"; //instance variable initializers are allowed // assignment statement aValue = 8933.234; // not allowed // increment statement aValue++; // not allowed // method invocation statement System.out.println("Hello World!"); // not allowed // object creation statement Bicycle myBike = new Bicycle(); //instance variable initializers are allowed public void greet() { greetSomeone("mundo"); } public void greetSomeone(String someone) { name = someone; System.out.println("Hola, " + name); } };
希望这可以帮助.