内部类存在的意义:
1.实现了内聚的效果.
2.inner class 具有访问其外围类的权限,而不论其外围类中属性的权限
3.静态的内部内只能访问外围类中得静态成员变量
4.内部内都能独立的继承自一个(接口的)实现,所以无论外围类是否已经继承了某个(接口的)实现,对于内部类都没有影响
5.内部类可以作为实现java 多继承的一种有效方法。
例子:
先创建一个interface
package Callbacks;
public interface Incrementable {
void increment();
}
再创建两个类Callee1继承这个Incrementable
package Callbacks;
public class Callee1 implements Incrementable{
private int i = 0;
public Callee1() {
// TODO Auto-generated constructor stub
}
public void increment() {
// TODO Auto-generated method stub
i++;
System.out.println(i);
}
}
假如存在一个如下的类MyIncrement:
<pre name="code" class="java">package Callbacks;
public class MyIncrement {
public MyIncrement() {
// TODO Auto-generated constructor stub
}
public void increment() {
System.out.println("Other operate");
}
static void f(MyIncrement mi) {
mi.increment();
}
}
我们不难看出MyIncrement 具有与接口Incrementable 同样的方法,不过,它的意义已经完全不同于接口了,此时
如果需要定义一个类,把必须以MyIncrement为父本,而又要继承通用的接口Incrementable,那这个时候内部类开始起作用了.为了实现意义完全不同的接口,所以可以使用内部类,如callee2.
如下的 <span style="font-family: Arial, Helvetica, sans-serif;">Callee2:</span>
package Callbacks;
public class Callee2 extends MyIncrement{
private int i = 0;
public Callee2() {
// TODO Auto-generated constructor stub
}
public void increment() {
super.increment();
i++;
System.out.println(i);
}
private class Closure implements Incrementable {
public void increment() {
// TODO Auto-generated method stub
Callee2.this.increment();
}
}
Incrementable getCallbackReference() {
return new Closure();
}
}
另外,我们可以使用内部类来实现callback的设计模式。如下所示:
package Callbacks;
public class CallerTest {
public CallerTest() {
// TODO Auto-generated constructor stub
}
private Incrementable callbackRefrence;
CallerTest(Incrementable cbh) {
callbackRefrence = cbh;
}
void go() {
callbackRefrence.increment();
}
}
package Callbacks;
public class Callbacks {
public Callbacks() {
// TODO Auto-generated constructor stub
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Callee1 cl = new Callee1();
Callee2 c2 = new Callee2();
MyIncrement.f(c2);
CallerTest caller1 = new CallerTest(cl);
CallerTest caller2 = new CallerTest(c2.getCallbackReference());
caller1.go();
caller1.go();
caller2.go();
caller2.go();
}
}
这些基本上是内部类所具有的特征.
从表面上看,内部类是可以无条件的访问外部内的所有对象。而且内部类可以看成是java 对于不支持多继承的一个弥补