首页 > 代码库 > java中的内部类

java中的内部类

innerclass分为四种

一.staticinnerclass(静态内部类)

 1.the simplest form of inner class
 2.Can‘t hava the same name as the enclosing class
 3.Compiled into a comletely separate .class file from the out class
 4.Can acess only statci members and methods fo the enclosing calss ,including private static members
 5.Create an instance of a static inner class out of enclosing class  :new outerclass.innerclass()

package innerClass;
class staticInner
{
   private static  int  n=10;
   public static  void  dosomething()
   {
	   System.out.println(n);
   }
	public static class Inner
	{
		
		public void test()
		{
			System.out.println(n);
			 dosomething();
		}
	}
}
public class staticInnerClassTest{
	
	public static void main(String[] args) {
		staticInner.Inner inner=new staticInner.Inner();
		inner.test();
	}
}

上面第四点,只能访问包含他的类的静态成员变量和静态方法  例如上面的 inner类 只能访问 n变量 和staticdosomething方法

如果把上面的的定义变量n和方法的修饰符static去掉 就会出错,例如去掉变量n前的static修饰符 错误提示为Cannot make a static reference to the non-static field n

不能使一个静态n引用为非静态字段,差不多就是这个意思,就是不能访问包含它的类的非静态字段和方法