java基础——内部类


内部类

如果A类需要直接访问B类中的成员,而B类又需要建立A类的对象。这时,为了方便设计和访问,直接将A类定义在B类中。就可以了。A类就称为内部类。内部类可以直接访问外部类中的成员。而外部类想要访问内部类,必须要建立内部类的对象。

内部类的访问规则
1,内部类可以直接访问外部类中的成员,包括私有。
之所以可以直接访问外部类中的成员,是因为内部类中持有了一个外部类的引用,格式 外部类名.this
2,外部类要访问内部类,必须建立内部类对象。

访问格式
1,当内部类定义在外部类的成员位置上,而且非私有,可以在外部其他类中。
可以直接建立内部类对象。
格式
外部类名.内部类名  变量名 = 外部类对象.内部类对象;

Outer.Inner in = new Outer().new Inner();

<pre name="code" class="java">class Outer
{
	private static  int x = 3;
	class Inner
	{
		void function()
	{
	System.out.println("innner :"+x);
}

class InnerClassTest 
{
	public static void main(String[] args) 
	{
		Outer.Inner in = new Outer().new Inner();
		in.function();
	}
}


 2,当内部类在成员位置上,就可以被成员修饰符所修饰。 
比如:private:将内部类在外部类中进行封装。 
static:内部类就具备static的特性。 
当内部类被static修饰后,只能直接访问外部类中的static成员。出现了访问局限。 
在外部其他类中,如何直接访问static内部类的非静态成员呢? 
new Outer.Inner().function(); 

class Outer
{
	private static int x = 3;	
	static class Inner
	{
		void function()
		{
			System.out.println("innner :"+x);
		}
	}
}

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

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

class Outer
{
	private static int x = 3;	
	static class Inner
	{
		static void function()
		{
			System.out.println("innner :"+x);
		}
	}
}

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

注意 :当内部类中定义了静态成员,该内部类必须是static的。
 当外部类中的静态方法访问内部类时,内部类也必须是static的。

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

class Outer
{
	int x = 3;

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

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

匿名内部类:
1,匿名内部类其实就是内部类的简写格式。
2,定义匿名内部类的前提:
内部类必须是继承一个类或者实现接口。
3,匿名内部类的格式:  new 父类或者接口(){定义子类的内容}
4,其实匿名内部类就是一个匿名子类对象。而且这个对象有点胖。 可以理解为带内容的对象。
5,匿名内部类中定义的方法最好不要超过3个。

继承一个类

abstract class AbsDemo
{
	abstract void show();
	
}

class Outer
{
	int x = 3;
	public void function()
	{
		AbsDemo d = new AbsDemo()
		{
			int num = 9;
			void show()
			{
				System.out.println("num=="+num);
			}
			void abc()
			{
				System.out.println("haha");
			}
		};

		d.show();
	}
}

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

实现一个接口

interface Inter
{
	void method();
}

class Test 
{
	static Inter function()
	{
		return new Inter()
		{
			public void method()
			{
				System.out.println("method run");
			}
		};
	}
}
class InnerClassTest 
{
	public static void main(String[] args) 
	{
			 Test.function().method();
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值