1. Java中innerClass内部类
class="java">
用AA.BB可以生成内部类,在编译的时候用AA$BB.class来表示。
class StaticInner{
private static int a = 4;
public static class Inner{
public void test(){
System.out.println(a);
}
}
}
public class StaticInnerClassTest {
public static void main(String[] args) {
StaticInner.Inner inner = new StaticInner.Inner();
inner.test();
}
}
运行结果:
4
1) 静态内部类(static inner class):只能访问外部类的静态成员变量与静态方法,生成静态内部类对象的方式为:
OuterClass.InnerClass inner = new OuterClass.InnerClass();
class MemberInner{
private int a = 4;
public class Inner2{
private int a = 5;
public void doSomething(){
System.out.println(MemberInner.this.a);
}
}
public void method(){
Inner2 inner = this.new Inner2();
}
}
public class MemberInnerClassTest {
public static void main(String[] args) {
MemberInner.Inner2 inner = (new MemberInner()).new Inner2();
inner.doSomething();
}
}
用(new AA()).new BB()类生成内部类,访问成员变量时,用OuterClass.this.aaa访问外部类的变量。
MemberInner.Inner2 inner = (new MemberInner()).new Inner2();
2) 成员内部类(memberinnerclass):可以访问外部类的静态与非静态的方法与成员变量。生成成员内部类对象的方式为:
OuterClass.InnerClassinner = newOuterClass().newInnerClass();
class LocalInner{
public void doSomething(){
final int a = 4;
class Inner3{
public void test(){
System.out.println(a);
}
}
new Inner3().test();
}
}
public class LocalInnerClassTest {
public static void main(String[] args) {
LocalInner localInner = new LocalInner();
localInner.doSomething();
}
}
LocalInner localInner = new LocalInner();
localInner.doSomething(); 想要访问内部类,就调用外部类的方法。
3) 局部内部类(LocalInnerClass):定义在方法当中,只能访问方法中声明的final类型的变量。
import java.util.Date;
public class AnonymousInnerClassTest {
@SuppressWarnings("deprecation")
public String get(Date date){
return date.toLocaleString();
}
public static void main(String[] args) {
AnonymousInnerClassTest test = new AnonymousInnerClassTest();
// String str = test.get(new Date());
// System.out.println(str);
String str = test.get(new Date(){
public String toLocalString(){
return "hello world";
}
});
System.out.println(str);
}
}
编译时生成生成AnonymousInnerClassTest$1.class。
4) 匿名内部类(Anonymous Inner Class) :匿名内部类会隐式地继承一个父类或实现一个接口。
匿名内部类实现actionPerformed方法的监听器的监听
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
public class SwingTest {
public static void main(String[] args) {
JFrame frame = new JFrame("JFrame");
JButton button = new JButton("click me");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("welcome");
}
});
frame.setSize(200, 200);
frame.getContentPane().add(button);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frame.setVisible(true);
}
}