内部类:内部类可以派生出一个类,但是因为内部类的存在必须依赖于其外部类的某一个对象,因此需要用到一种特殊的语法.super()来建立内部类和其某一外部对象的关联。写了一段代码如下,这是一个让人比较崩溃的hello,world
-------------------------
class a
{
class b
{
void pr()
{
System.out.println("hello,world");
}
}
}
class test extends a.b
{
test(a ex)
{
ex.super();
}
public static void main(String[] args)
{
a ex=new a();
test t=new test(ex);
t.pr();
}
}
内部类也可以实现某一个接口。
JAVA中不允许类的多继承,但是如果在类的内部多搞点内部类,每个内部类继承一个类,它也可以实现类似多继承的效果。
自己写了一段代码,让一个类继承了2个类还实现了一个接口,当然这都是借助于内部类来实现的。第一次写这么长的JAVA代码,碰到了点小麻烦,不过还好它最后还是运行出来了。
interface Machine
{
void run();
}
class person
{
void run()
{
System.out.println("person is running");
}
}
class computer
{
void run()
{
System.out.println("computer is ready now");
}
}
class robot extends person
{
class middle implements Machine
{
public void run()
{
System.out.println("machine is running now");
}
}
class inner extends computer
{
}
middle getmiddle()
{
return new middle();
}
inner getinner()
{
return new inner();
}
}
class test
{
public static void main(String[] args)
{
robot r=new robot();
Machine m=r.getmiddle();
robot.inner i=r.getinner();
r.run();
m.run();
i.run();
}
}
还有一种匿名内部类,它可以用于直接返回接口名或者虚类名,实现的方法是在接口名或者虚类名的后面分号之前,大括号内,实现接口中的成员和虚类中的成员。那么实质上返回的将是一个没有名字的类。这个搞得真的有点“只可意会,不能言传”了。
这个格式是return interface()
{
};
代码如下,这次是一个hello,tiger
interface animal
{
void run();
}
class tiger
{
animal getobject()
{
return new animal()
{
public void run()
{
System.out.println("hello,tiger");
}
};
}
}
class test1
{
public static void main(String[] args)
{
tiger t=new tiger();
animal a=t.getobject();
a.run();
}
}
内部类的学习就到这里告一段落了,有内部类的派生,用内部类来实现类似的多继承,内部类实现接口等等。