您的位置:首页 > 编程语言 > Java开发

Java内部类

2015-12-12 21:15 375 查看

Java内部类

1、内部类的访问规则

外部类要访问内部类,必须建立内部类对象。
/**
 * 
 */
package ex01;

/**
 * @author husheng
 *
 */

class Outer//外部类
{
	private int x = 3;
	
	class Inner//内部类
	{
		int x = 4;
		void function()
		{
			int x = 6;
			System.out.println("hello world!");
		}
	}

	void method()
	{
		Inner in = new Inner();
		in.function();
	}
}

class ex01//外部其他类
{
	public static void main(String[] args) 
	{
		Outer out = new Outer();
		out.method();
	}
}


内部类可以直接访问外部类中的成员,包括私有。
/**
 * 
 */
package ex01;

/**
 * @author husheng
 *
 */

class Outer//外部类
{
	private int x = 3;
	
	class Inner//内部类
	{
		int x = 4;
		void function()
		{
			int x = 6;
			System.out.println("x="+x);
		}
	}

	void method()
	{
		Inner in = new Inner();
		in.function();
	}
}

class ex01//外部其他类
{
	public static void main(String[] args) 
	{
		Outer out = new Outer();
		out.method();
	}
}


我们依次把输出语句改为:
System.out.println("x="+x);



System.out.println("x="+this.x);



System.out.println("x="+Outer.this.x);



直接访问内部类中的成员。
class Outer//外部类
{
	private int x = 3;
	
	class Inner//内部类
	{
		int x = 4;
		void function()
		{
			int x = 6;
			System.out.println("hello world!");
		}
	}
}

class ex01//外部其他类
{
	public static void main(String[] args) 
	{
		Outer.Inner in = new Outer().new Inner();
		in.function();
	}
}


2、静态内部类

内部类就具备static的特性。

在外部其他类中,如何直接访问static内部类的非静态成员呢?

new Outer.Inner().function();

在外部其他类中,如何直接访问static内部类的静态成员呢?

Outer.Inner.function();

注意:当内部类中定义了静态成员,该内部类必须是static的。

当外部类中的静态方法访问内部类时,内部类也必须是static的。

3、局部内部类

内部类定义在局部时,不可以被成员修饰符修饰。可以直接访问外部类中的成员,因为还持有外部类中的引用。但是不可以访问它所在的局部中的变量。只能访问被final修饰的局部变量。

/**
 * 
 */
package ex01;

/**
 * @author husheng
 *
 */

class Outer
{
	void method(final int a)
	{
		class Inner
		{
			void function()
			{
				System.out.println(a);
			}
		}
		new Inner().function();
		
	}
}

class  ex01
{
	public static void main(String[] args) 
	{
		Outer out = new Outer();
		out.method(7);
		out.method(8);
	}
}


4、匿名内部类

匿名内部类其实就是内部类的简写格式。

定义匿名内部类的前提:内部类必须是继承一个类或者实现接口。

匿名内部类的格式: new 父类或者接口(){定义子类的内容}

其实匿名内部类就是一个匿名子类对象。

/**
 * 
 */
package ex01;

/**
 * @author husheng
 *
 */

abstract class AbsDemo
{
	abstract void show();
	
}

class Outer
{
	public void function()
	{
		new AbsDemo()
		{
			void show()
			{
				System.out.println("hello world!");
			}
		}.show();
	}
}

class ex01 
{
	public static void main(String[] args) 
	{
		new Outer().function();
	}
}


====================================================================================
结束。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: