工学1号馆

home

4种类型的Java内部类

By Wu Yudong on November 02, 2015

在java中有四种类型的内部类,下面给出它们的名字和相应的实例

1. Static Nested Classes

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. Member Inner Class

成员类是具体实例,可以访问所有的方法、域、和外部类的引用.

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. Method-Local Inner Classes

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();
	}
}

x is static outer

4. Anonymous Inner Classes(匿名内部类)

这种内部类经常用在当你想给GUI应用的小组件增加事件监听的时候使用

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

如果文章对您有帮助,欢迎点击下方按钮打赏作者

Comments

No comments yet.
To verify that you are human, please fill in "七"(required)