【JAVA学习路-think in java】p191:如何创建内部类详解

总结:

创建内部类的方法:

  • static方法中,类名必须(存疑)如此声明:OuterClassName.InnerClassName obj_inner,但在非static方法中,也可以用
  • static方法中,不能使用 new InnerClassName(),但是在非static方法中,可以使用new InnerClassName()
  • 一言以蔽之,非static方法中比较灵活、包容,但在static方法中则比较受限。

 

package pkg;
public class p190 {
	
	// .. class ..
	//1st
	class Contents{
		private int i=11;
		public int value() {return i;}
	}
	// 2nd 
	class Destination{
		private String label="NUll";
		public Destination(String wherego) {
			label=wherego;
		}
		String readLable() {return label;}
	}
	
	
	// .. function .. 
	//USING class Contents and Destination as USUAL
	public void ship(String desti) {
		Contents c=new Contents();
		Destination d=new Destination(desti);
		System.out.println(d.readLable());
		
		p190.Destination d2=new Destination("...Hongkong ");//this is allowed
		System.out.println(d2.readLable());
		
	}
	
	//..new add function
	public Contents content() {
		return new Contents();
	}
	public Destination to(String s) {
		return new Destination(s);
	}
	
	
	//.. main ..
	public static void main(String[] args) {
		//usually
		p190 p=new p190();
		p.ship("HongKong");
		
		//using INNER Class
		p190 p2=new p190();
		
		p190.Contents c=p2.content();//How to create a inner Class	
		p190.Destination d=p2.to("ShenZhen");
		System.out.println(d.readLable());
		
		//p190.Contents c3=new Contents();//this is  NOT allowed
		Destination d2=p2.to("Wuhan");//why??? conflict with page 191
		System.out.println(d2.readLable());

	}
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值