如果方法的参数被定义一个接口类型,那么就需要定义一个类来实现这个接口,并根据该类进行实例化对象,除此之外还可以使用匿名内部类来实现接口,为了让初学者能更好地理解什么是匿名内部类,接下来将举一个内部类实现接口的例子
interface Animal{
void shout();
}
public class Main{
public static void main(String[] args){
class Cat implements Animal{
public void shout(){
System.out.println("喵喵,,,");
}
}
animalShout(new Cat());//此时的参数实际为Cat对象
}
private static void animalShout(Animal cat) {
cat.shout();
}
}
在上例中内部类Cat实现了接口Aniaml,在调用animalShout()方法时将Cat类的实例对象作为参数传入。
接下来演示使用匿名内部类来实现上例中的代码功能
首先内名内部类的格式具体如下:
new 父类或父接口(){
//内部实现部分
}
完整代码:
interface Animal{
void shout();
}
public class Main{
public static void main(String[] args){
animalShout(new Animal(){
public void shout(){
System.out.println("喵喵,,,");
}
});
}
private static void animalShout(Animal cat) {
cat.shout();
}
}