在Java中,內(nèi)部類有四種不同的類型。這篇文章用四個簡單的例子來闡明它們。
1.靜態(tài)嵌套類
class Outer {
static class Inner {
void go() {
System.out.println("Inner class reference is: " + this);
}
}
}
public class Test {
public static void main(String[] args) {
Outer.Inner n = new Outer.Inner();
n.go();
}
}
輸出:
Inner class reference is: Outer$Inner@19e7ce87
2.成員內(nèi)部類
成員類是特定于實(shí)例的。 它可以訪問所有的方法得封,字段和其他的外部類的引用。
public class Outer {
private int x = 100;
public void makeInner(){
Inner in = new Inner();
in.seeOuter();
}
class Inner{
public void seeOuter(){
System.out.println("Outer x is " + x);
System.out.println("Inner class reference is " + this);
System.out.println("Outer class reference is " + Outer.this);
}
}
public static void main(String [] args){
Outer o = new Outer();
Inner i = o.new Inner();
i.seeOuter();
}
}
輸出:
Outer x is 100
Inner class reference is Outer$Inner@4dfd9726
Outer class reference is Outer@43ce67ca
3.方法內(nèi)部類
public class Outer {
private String x = "outer";
public void doStuff() {
class MyInner {
public void seeOuter() {
System.out.println("x is " + x);
}
}
MyInner i = new MyInner();
i.seeOuter();
}
public static void main(String[] args) {
Outer o = new Outer();
o.doStuff();
}
}
輸出:
x is outer
public class Outer {
private static String x = "static outer";
public static void doStuff() {
class MyInner {
public void seeOuter() {
System.out.println("x is " + x);
}
}
MyInner i = new MyInner();
i.seeOuter();
}
public static void main(String[] args) {
Outer.doStuff();
}
}
4.匿名內(nèi)部類
當(dāng)你在一個GUI程序中指郁,為一個widget添加一個動作監(jiān)聽器的時(shí)候常被用到忙上。
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
comp.setText("Button has been clicked");
}
});