编辑代码

class Main {
    //内部类的定义和使用示例
	public static void main(String[] args) {
        //JSRUN引擎2.0,支持多达30种语言在线运行,全仿真在线交互输入输出。
		Parcel p = new Parcel();
        Parcel.Contents c = p.new Contents(33);
        // D行
        Parcel.Destination d = p.new Destination("山西大同");
        // A行
        // Destination d = new Destination("山西太原");
        p.setValue(c,d);
        p.ship();
        p.testShip();
	}
}

class Parcel {
    // Contents 是类型,所以 c 是对象
    // private只能在当前类内被访问,所以他的作用范围在类Parcel内
    private Contents c;
    private Destination d;
    private int contentsCount = 0;
    // 这是构造了内部类
    class Contents{
        private int i;
        Contents(int i){
            this.i = i;
            // parcel的成员变量
            contentsCount++;
        }
        int value(){
            return i;
        }
    }
    // 外层的成员变量和成员方法能在内部被作用
    class Destination{
        private String label;
        Destination(String whereTo){
            label = whereTo;
        }
        String readLabel(){
            return label;
        }
    }
    // 传入了parcel的两个成员变量
    void setValue(Contents c,Destination d){
        // 对 c 和 d 进行初始化
        this.c = c;
        this.d = d;
    }
    void ship(){
        // B行
        // c.value() 是调用方法,在相同包的非子类内被访问 这是一个默认访问控制符
        System.out.println("运输"+c.value()+"到"+d.label);
        // label是内部类所定义的,都属于Parcel,所以在Parcel的整个作用范围内都有效
        // 所以可以总结,private在内部类中的作用范围有扩大
    }
    public void testShip(){
        c = new Contents(22);
        d = new Destination("山西太原");
        ship();
    }
}