内部类

/*
内部类的访问规则:
1、内部类可以直接访问外部类的成员,包括私有成员,之所以可以直接访问外部类成员,是因为内部类中持有一个外部类的引用,格式:外部类名称.this
2、外部类要访问内部类,必须要建立内部类对象
	一般我们都将内部类私有化进行封装起来。
访问格式:
当内部类定义在外部类的成员位置时,而且是非私有,可以再外部其他类中直接建立内部类对象。
格式:
	外部类名.内部类名   变量名 = 外部类对象.内部类对象;
	Outer.Inner in=new Outer().new Inner();
2、当内部类在成员变量位置上时可以被成员变量修饰符修饰,比如,private:将内部类在外部类中进行封装,static:内部类就具有static特性。
	当内部类被static修饰后,只能直接访问外部类中的静态成员,出现访问局限,

	在外部其他类中,如何直接访问static内部类的非静态成员呢?
	new Outer.Inner().funtion();

	在外部其他类中,如何直接访问static内部类的静态成员呢?
	Outer.Inner.function();
	注意:当内部类中定义了静态成员,该内部类必须是静态类。
	当外部静态方法访问内部类时,内部类必须为惊天。
*/

class Outer
{
	private int x = 3;
	class Inner
	{
		int x=4;
		void function()
		{
			int x=7;
			System.out.println(x);					//输出7
			System.out.println(this.x);				//输出4
			System.out.println(Outer.this.x);		//输出3
							    //上面定义的三个变量x,是种特殊情况,一般如果没有this类的指定修饰,直接输出x。采取的就近原则
    <span style="white-space:pre">	</span>						   //注释int x=7,那么println(x)和println(this.x)是一样的												  //注释int x=4,那么println(this.x)是错误的,因为内部类没有成员x
		}
	}

	static class Inner2
	{
		static int y=10;
		void function()
		{
			System.out.println("静态内部类。");
		}
	}

	void method()									//外部类成员访问内部类
	{
		Inner in=new Inner();
		in.function();
	}
}
class InnerDemo 
{
	public static void main(String[] args) 
	{
		Outer outer=new Outer();
		outer.method();					//访问外部类中成员

		Outer.Inner in=new Outer().new Inner();			//创建内部类对象
		in.function();

		System.out.println(Outer.Inner2.y);             //访问静态内部类中的静态成员
		new Outer.Inner2().function();					//访问静态类中的非静态成员.
	}
}

posted @ 2015-01-03 13:34  静以养身 俭以养德  阅读(165)  评论(0编辑  收藏  举报