Java的内部类分为四种:
static inner class:可以访问static变量和方法
inner class:可以访问static变量和方法;可以访问类变量和类方法
local class:可以访问final变量,static变量和方法;如何在非static方法中,可以访问类变量和类方法
anonymous class:可以访问final变量,static变量和方法;如何在非static方法中,可以访问类变量和类方法
下面时它们的使用方法:
OuterClass.java
public class OuterClass {
static class StaticNestedClass {
public void printIt() {
System.out.println("StaticNestedClass");
}
}
class InnerClass {
public void printIt() {
System.out.println("InnerClass");
}
}
public static void main(String[] args) {
StaticNestedClass c1 = new StaticNestedClass();
c1.printIt();
}
}
Test.java
import other.OuterClass.InnerClass;
import other.OuterClass.StaticNestedClass;
public class Test {
public static void main(String[] args) {
StaticNestedClass c1 = new StaticNestedClass();
c1.printIt();
OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
nestedObject.printIt();
//inner class
OuterClass oc = new OuterClass();
InnerClass c2= oc.new InnerClass();
c2.printIt();
class LocalClass {
public void printIt() {
System.out.println("LocalClass");
}
}
LocalClass lc = new LocalClass();
lc.printIt();
LocalClass lc2 = new LocalClass() {
@Override
public void printIt() {
System.out.println("AnonymousClass");
}
};
lc2.printIt();
PrintInterface pi = new PrintInterface() {
@Override
public void printIt() {
System.out.println("AnonymousClass2");
}
};
pi.printIt();
}
interface PrintInterface {
public void printIt();
}
}
以下时屏幕输出:
StaticNestedClass
StaticNestedClass
InnerClass
LocalClass
AnonymousClass
AnonymousClass2