3.6 Java内部类四种类型

在Java中,内部类有四种不同的类型。这篇文章用四个简单的例子来阐明它们。

1.静态嵌套类

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.成员内部类

成员类是特定于实例的。 它可以访问所有的方法,字段和其他的外部类的引用。

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.方法内部类

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.匿名内部类

当你在一个GUI程序中,为一个widget添加一个动作监听器的时候常被用到。

button.addActionListener(new ActionListener(){
     public void actionPerformed(ActionEvent e){
         comp.setText("Button has been clicked");
     }
});

你可能感兴趣的:(3.6 Java内部类四种类型)