没有名字的类就叫做匿名类。
有些时候,我们并不关心类的名字叫啥,只是想用类中的方法,这个时候我们就可以使用匿名类来操作了。
public class AnonymousClassTest {
public static void main(String[] args){
Person p = new Person();
p.wear(new MyGlass());
p.wear(new MyGlass(){
String test(){
return "red";
}
});
p.wear(new MyGlass(){
String test(){
return "black";
}
});
((Fly) () -> System.out.println("fly with you")).fly();
new Fly(){
public void fly(){
System.out.println("fly with she");
}
}.fly();
}
}
abstract class Glass{
abstract String test();
}
class MyGlass extends Glass{
String test(){
return "yellow";
}
}
class Person{
void wear(MyGlass myGlass){
System.out.println("I wear glass, and the glass color is that:"+ myGlass.test());
}
}
interface Fly{
public void fly();
}