</pre><pre name="code" class="java">public class Test {
//java内部类分为: 成员内部类、静态嵌套类、方法内部类、匿名内部类。
//其中成员内部类和静态嵌套类需要在外部类中调用。调用的时候比较麻烦,本文主要针对这两种内部类外部调用做分析。
//方法内部类只能在定义该内部类的方法内对其实例化;匿名内部类定义的时候直接创建该类对象。
//成员内部类Test1
class Test1 {
int i;
public Test1(int i) {
this.i = i;
System.out.println("内部类1测试");
}
public int fun1() {
return i;
}
}
//成员内部类Test2
class Test2 {
int i;
public Test2(int i) {
this.i = i;
System.out.println("内部类2测试");
}
public int fun2() {
return i;
}
}
//静态内部类。静态内部类中可以定义静态或者非静态的成员。//静态内部类不能访问外部类的非静态成员或非静态方法。
static class Test3 {
public int i = 4;
public static int m = 3;
public static void fun3() {
System.out.println(m);
}
public void fun4() {
System.out.println(m);
}
}
//非静态方法可以调用静态或者非静态的变量或者方法。
public void fun5() {
//非静态方法中,对于成员内部类:可以“new外部类.new内部类"或者“new内部类”来访问。
//非静态方法中new出来的成员内部类的类型可以是“外部类.内部类”或者“内部类”。
Test.Test1 m = new Test1(5);
System.out.println(m.fun1());
Test2 n = new Test().new Test2(10);
System.out.println(n.fun2());
//非静态方法中,对于静态内部类:可以“内部类.XX”或者“外部类.内部类.XX”或者“new内部类”来访问,不可以“new外部类new内部类”来访问
//非静态方法中访问静态内部类中的静态成员或者静态方法用“内部类.XX”访问
Test3.fun3();
System.out.println(Test.Test3.m);
//非静态方法中访问静态内部类中的非静态成员或者非静态方法用“new 静态内部类”,然后访问
new Test3().fun4();
System.out.println(new Test3().i);
//new出来的静态内部类的类型可以是“外部类.内部类”或者“内部类”
Test.Test3 tt = new Test3();
tt.fun3();
Test3 ttt = new Test3();
ttt.fun4();
}
//“静态方法中访问成员内部类的操作”与“静态方法中访问非静态成员或者非静态方法的操作”类似,“new 外部类.new 成员内部类”,然后访问。
//"静态方法中访问静态内部类的操作"与"静态方法中访问静态成员或者静态方法的操作"类似,可直接通过"静态内部类.XX"调用。
//不过静态内部类可以定义非静态成员和方法,如果要访问静态内部类中的非静态成员或者非静态方法,则需要“new 静态内部类”,然后访问。
public static void main(String[] args) {
//不能如下访问成员内部类,必须先new外部类
//Test.Test1 t4 = new Test1(8);
Test.Test1 t1 = new Test().new Test1(8);
System.out.println(t1.fun1());
//main静态方法中new出来的成员内部类t2的类型可以为“外部类.内部类”,也可以为“内部类”
Test2 t2 = new Test().new Test2(7);
System.out.println(t2.fun2());
Test t3 = new Test();
t3.fun5();
//通过静态内部类名直接调用静态变量或者静态方法
Test3.fun3();
System.out.println(Test.Test3.m);
//访问静态内部类中的非静态成员或者非静态方法需要new静态内部类,然后访问
System.out.println(new Test3().i);
new Test3().fun4();
//报异常
//Test3.fun4();
//main静态方法中new出来的静态内部类tt的类型可以为“外部类.内部类”,也可以为“内部类”
Test3 tt = new Test3();
System.out.println(tt.i);
Test.Test3 ttt = new Test3();
//静态内部类中的静态方法也可以“new静态内部类.静态方法()”如此访问。
ttt.fun3();
}
}
成员内部类不能含有static的变量和方法。因为成员内部类需要先创建了外部类,才能创建它自己。静态内部类不能访问外部类的非静态成员或非静态方法。
普通内部类不能有static数据和static属性,也不能包含嵌套类,但嵌套类可以。而嵌套类不能声明为private,一般声明为public,方便调用.
一个java文件中只能有一个public类,但是一个类里面可以有多个public内部类。
总结:
静态内部类,我们只要"new 内部类.xx"就不会出错(不过一般需要静态内部类的时候都针对内部类里面的静态成员或者静态方法而言,会“内部类.XX")
成员内部类,我们只要“new外部类.new内部类”就不会出错。
new出来的内部类的通用类型只要是“外部类.内部类”就不会出错
原文地址:http://blog.csdn.net/qq1623267754/article/details/36588885