匿名内部类

                        匿名内部类

当然上一代码中我们没有必要去直接返回new Tiger(),还有如下做法:

代码
interface Animal {
void eat();
void sleep();
}

class Zoo {
class Tiger implements Animal {
public void eat() {// 其实我强烈建议将实现方法写在匿名内部类中。
System.out.println("tiger eat");
}

public void sleep() {
System.out.println(
"tiger sleep");
}
}

/*Animal getAnimal() {
return new Tiger();
}
*/

Animal getAnimal() {
return new Animal(){
public void eat() {
System.out.println(
"animal eat");
}

public void sleep() {
System.out.println(
"animal sleep");
}
};
// 一个接口怎么能直接去实例化呢?除非去实现接口中的方法
}
}

class Test {
public static void main(String[] args) {
Zoo z
= new Zoo();
Animal an
= z.getAnimal();
an.eat();
an.sleep();
}
}

 

Anonymous inner class are local inner classes that don't have a class name.
匿名内部类是局部的内部类,它没有名字。
You use an anonymous class when you want to create and use a class but don't
want to bother with giving it a name or using it again.
当你想要创建并使用一个类但是你不想要因为一次又一次的命名而困惑的时候就可以使用一个匿名的类。
When use an anonymous inner class ,the keyword class is missing,and there are
当使用一个匿名的内部类的时候,在这个类中不能有关键字,也没有
no modifers(public,protected,and so on). The kewords extends and implements are
访问修饰符(例如public,protected,等等)。继承(extends)和实现(implements)关键字也不能有。
missing too. These keywords aren't allowed because we create anonymous inner
这些关键字之所以不允许,是因为创建一个匿名的内部类
class through another extension to the new operator syntax. That means the complete
是通过其它扩展性的操作语法new 对象的。也就是说完整的类的
class definition is actually part of a java expression. Right after the
定义是真正java表达式的一部分。在实例化某个类(new someClass())语法之后,
new someClass() syntax,you write a curly brace and start to write a class definition.
你写了一个{,然后开始写一个类的声明,这样是正确的。(curly brace 是花括号的意思。这句话的意思就是:new someClass(){Add code here};)
It's that simple.
那是非常的简单。
The lack of a class name has a number of implications for the definition and use of
弱的类名称有一个牵连(引用)数字指向定义并使用内部类。
inner classes.You can't define contructors for an anonymous inner class because
你不能为一个匿名的内部类定义一个构造方法,因为
you can't name them. They must always (implicitly) extend a superclass or implements
你不能给它们的构造方法命名。它们必须通常的(绝对地)继承一个父类或者实现
some interface,even though you never use the extends or implements keywords.
某个接口,即使你没有使用继承或者实现关键字。

posted @ 2010-12-21 14:37  meng72ndsc  阅读(592)  评论(0编辑  收藏  举报