java匿名内部类创建
时间: 2023-12-13 11:31:17 浏览: 97
Java中可以使用匿名内部类来创建实现某个接口或继承某个类的对象。匿名内部类的语法格式为:new 父类构造器或接口() { 匿名内部类的类体 }。下面是一个例子:
```java
public class AnonymousInnerClassExample {
interface HelloWorld {
void greet();
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";
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";
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) {
AnonymousInnerClassExample myApp =
new AnonymousInnerClassExample();
myApp.sayHello();
}
}
```
在上面的例子中,我们定义了一个接口HelloWorld,然后使用匿名内部类来实现这个接口。我们创建了三个HelloWorld对象,分别是EnglishGreeting、frenchGreeting和spanishGreeting。其中,EnglishGreeting是一个普通的内部类,而frenchGreeting和spanishGreeting是匿名内部类。我们可以看到,使用匿名内部类可以简化代码,并且不需要单独定义一个类。
阅读全文