首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

问一个java 接口和内部类的有关问题 真的有点搞不清

2012-01-22 
问一个java接口和内部类的问题真的有点搞不清interface Animal{void eat()void sleep()}class Zoo{priva

问一个java 接口和内部类的问题 真的有点搞不清
interface Animal
{
void eat();
void sleep();
}

class Zoo
{
private class Tiger implements Animal
{
public void eat()
{
System.out.println("tiger eat");
}
public void sleep()
{
System.out.println("tiger sleep");
}
}

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();
}
}

这段代码可以运行 结果是animal eat和animal sleep 我有疑问 接口类不是不可以实例化吗?
为什么它这里可以用return new Animal然后再用一个匿名内部类会没有问题  

还有一段代码 如下
interface Animal
{
void eat();
void sleep();
}

class Zoo 
{
class Tiger implements Animal
{

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


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

an.eat();
an.sleep();

}
}
这段代码编译出错 说在第九行Zoo.Tiger is not abstract and does not override abstract method sleep()
in Animal 不知道这里为什么不行 应该怎么改 谢谢!

[解决办法]
1.
return new Animal() {

public void eat() {
System.out.println("animal eat");
}

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

这个不是返回Animal的实例,而是实现这个接口的类的实例,
public class AnimalImpl{

public void eat() {
System.out.println("animal eat");
}

public void sleep() {
System.out.println("animal sleep");
}
}
这么理解,然后return new AnimalImpl();

热点排行