/***
* 用匿名内部类实现
*
* @author xxx
*
*/
// 定义动物类的接口
interface Animal1 {
// 定义方法shout()
void shout();
}
public class InnerClassDemo2 {
public static void main(String[] args) {
// 定义一个内部类来实现Animal这个接口
class cat implements Animal1{
public void shout(){
System.out.println("喵喵……");
}
}
// 通过匿名内部类可以不定义内部类,直接实现Animal这个接口
// 定义匿名内部类作为参数传递给animalShout()的方法
animalShout(new Animal() {
// 实现shout()方法
public void shout() {
System.out.println("喵喵……");
}
});
}
public static void animalShout(Animal an) {
// 调用传入对象an的shout()方法
an.shout();
}
}
* 用匿名内部类实现
*
* @author xxx
*
*/
// 定义动物类的接口
interface Animal1 {
// 定义方法shout()
void shout();
}
public class InnerClassDemo2 {
public static void main(String[] args) {
// 定义一个内部类来实现Animal这个接口
class cat implements Animal1{
public void shout(){
System.out.println("喵喵……");
}
}
// 通过匿名内部类可以不定义内部类,直接实现Animal这个接口
// 定义匿名内部类作为参数传递给animalShout()的方法
animalShout(new Animal() {
// 实现shout()方法
public void shout() {
System.out.println("喵喵……");
}
});
}
public static void animalShout(Animal an) {
// 调用传入对象an的shout()方法
an.shout();
}
}