Java内部类依附于外部类的对象

今天仔细看了一下java的内部类,发现:

内部类是依附于外部类的对象,多个内部类也可以依附于同一个外部类对象

代码如下:

public class Outer {
	private int i=0;
	private void f()
	{
		System.out.println("This is Outer.f()");
	}
	
	Outer()
	{
		System.out.println("This is outer !");
		declear();
	}
	
	void declear() 
	{///外围类宣称身份
		System.out.println("I 'm "+i);
	}
	
	void ff()
	{///测试函数
		Inner t = new Inner(3);
		t.get_outer().declear();
		
		Inner x = new Inner(4);
		
		x.get_outer().declear();
		
		t.g();
		x.g();
	}
	class Inner
	{///内部类
		Inner(int x){i=x;}
		Inner(){System.out.println("This is Inner !");}
		void g()
		{
			System.out.println("I can Get The i from the outer "+i);
			f();
		}
		Outer get_outer()
		{///以此得到一个外围类的引用
			return Outer.this;
		}
	}
	public static void main(String[] args) {
		Outer p = new Outer();
		p.ff();
		Outer.Inner in = p.new Inner();
		in.get_outer().declear();
	}
}

运行结果如下 :

This is outer !
I 'm 0
I 'm 3
I 'm 4
I can Get The i from the outer 4
This is Outer.f()
I can Get The i from the outer 4
This is Outer.f()
This is Inner !
I 'm 4//证明main()中创建的内部类对象依附于p

当把函数ff()代码更改为:

void ff()
{///测试函数
		Inner t = new Inner(3);
		Inner x = new Inner(4);
		//调换了Inner x = new Inner(4);与t.get_outer().declear();的顺序
		t.get_outer().declear();
		x.get_outer().declear();
		
		t.g();
		x.g();
}

运行结果变成:

This is outer !
I 'm 0
I 'm 4//此处由3变为4,证明t与x修改的外部类对象是同一个
I 'm 4
I can Get The i from the outer 4
This is Outer.f()
I can Get The i from the outer 4
This is Outer.f()
This is Inner !
I 'm 4

以上足以说明:同一个外部对象进行操作创建的内部类对象,都依附于该外部类对象。

总结:

要充分理解内部类对象对外部类对象的依附(通过拥有外部类对象的引用来实现)

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值