Java中提供了内部类机制(Innner Class),是指将一个类的定义放在另一个类的内部,其中内部类可以访问包含它们外部类的域,内部类技术主要用于设计具有相互协作关系的类集合,在编写GUI事件的代码时会经常使用到内部类。内部类和组合是完全不同的概念。
为什么需要内部类?
public class Outer {
public int i = 10;
private String str = "outer class";
private class Inner {
private int i = 11;
public int getInner() {
return i;
}
public int getOuter() {
return Outer.this.i;
}
public String getOuterStr() {
return Outer.this.str;
}
}
public static void main(String[] args) {
Outer outer = new Outer();
// Inner inner = new Inner(); //这样创建内部类编译器会报错
Inner inner = outer.new Inner();
System.out.println(inner.getInner());
System.out.println(inner.getOuter());
System.out.println(inner.getOuterStr());
}
}
public Inner(Outer outer) {
this.outer = outer;
}
public class MethodInner {
private int i;
public MethodInner(int i) {
this.i = i;
}
public int method(int val) {
class InnerClass {
private int i;
public InnerClass(int i) {
this.i = i;
}
public int increment() {
return ++i;
}
}
InnerClass inner = new InnerClass(val);
return inner.increment() + add();
}
public int add() {
return ++i;
}
public static void main(String[] args) {
MethodInner mi = new MethodInner(5);
int i = mi.method(2);
System.out.println(i);
}
}
public class AnonymousClass {
public static void main(String[] args) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("It's runnable target...");
}
});
t.start();
}
}
public class AnonymousClass {
public static void main(String[] args) {
Target target = new Target();
Thread t = new Thread(target);
t.start();
}
}
class Target implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("It's runnable target...");
}
}
public class StaticInner {
private int i = 1;
private static String str = "outer";
private static class StaticInnerClass {
private int i = 11;
private String name;
public StaticInnerClass(String str) {
this.name = str;
}
public void say() {
System.out.println("outer : " + StaticInner.str);
System.out.println("inner : i=" + i + " - name=" + name);
}
}
public static void main(String[] args) {
StaticInnerClass inner = new StaticInnerClass("inner");
inner.say();
}
}