java的内部类

内部类

内部类:在一个类的内部嵌套其它类的操作叫内部类。

简单的内部类:

public class Outer {
	private String msg = "hello world";
	class Inner  //定义一个内部类
	{
		public void print()
		{
			System.out.println(msg);
		}
	}
	
	public void func()
	{
		Inner inner = new Inner();
		inner.print();
	}
}

public class MainTest {
	public static void main(String[] args) {
		Outer outer = new Outer();
		outer.func();
	}
}

引入内部类之后我们牺牲了程序的规范性,代码有些混乱。但是换来的却是内部类可以方便的操作外部类的私有属性。

针对上面的代码,我们可以修改为:

public class Outer {
	private String msg = "hello world";
	
	public String getMsg()
	{
		return this.msg;
	}
	
	public void func()
	{
		Inner inner = new Inner(this);  
        //this表示当前类的对象,类似C++拷贝构造时return的this
		inner.print();
	}
}

public class Inner {
	Outer out = new Outer();
	public Inner(Outer out)  //引用传递this.out = main.out
	{
		this.out = out;
	}
	
	public void print()
	{
		System.out.println(out.getMsg());
	}
}

public class MainTest {

	public static void main(String[] args) {
		Outer outer = new Outer();
		outer.func();
	}

}
  1. 内部类的访问只有通过外部类才可以完成。
  2. 如果一个内部类只想被外部类使用,可以使用private关键字。
  3. 进行属性访问时必须加上this。
static修饰内部类

内部类使用了static修饰,该内部类只允许访问外部类的static部分。

该内部类实例化的语句是:

外部类.内部类 内部类对象 = new 外部类.内部类();

eg:

public class Outer2 {
	private static String msg = "hello world";
	static class Inner
	{
		public void print()
		{
			System.out.println(msg);
		}
	}
	
	public void func()
	{
		Inner in = new Inner();
		in.print();
	}
}

public class TestMain {
	public static void main(String[] args) {
		Outer2.Inner in = new Outer2.Inner();
		in.print();
		
	}
}
在方法中定义内部类
public class Outer3 {
	private static String msg = "hello world";
	
	public void func(int num)
	{
		class Inner
		{
			public void print()
			{
				System.out.println("num: " + num);
				System.out.println("msg: " + msg);
			}
		}
		
		new Inner().print();
	}
}	

public class TestMain {
	public static void main(String[] args) {
		Outer3 out = new Outer3();
		out.func(33);
	}
}
内部类的特点:
  1. 破坏了程序的结构。
  2. 方便进行私有属性的访问。(外部类也可以访问内部类的私有域)
  3. 如果发现类名称上出现了"." ,应当立即想到内部类的概念。

暂时不推荐使用!

我想一直陪着你,小马同学。万事如意~

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值