您的位置:首页 > 其它

内部类——this和new及向上转型

2018-02-03 00:00 267 查看

一、.this

package com.lh.innerclass.class2;

public class DotThis {

public void f(){
System.out.println("DotThis.f()");
}

class Inner{
public DotThis outer(){
//调用当前外部类对象
return DotThis.this;
}
}

public Inner inner(){
return new Inner();
}

public static void main(String[] args) {
DotThis dotThis = new DotThis();
DotThis.Inner inner = dotThis.inner();
inner.outer().f();

System.out.println(dotThis == inner.outer());
}

}


二、.new

package com.lh.innerclass.class2;

public class DotNew {
class Inner{}

public static void main(String[] args) {
DotNew dotNew = new DotNew();

//创建内部类实例对象
DotNew.Inner inner = dotNew.new Inner();
}

}


三、内部类与向上转型

package com.lh.innerclass.class2.upward;

/***
*
*
* 内部类与向上转型(基类或接口,隐藏内部实现细节)
*
* @author Liu
*
*/
public class Parcel {
//定义为私有,外部无法访问
private class PContents implements Contents{
private int i = 11;

public int value(){
return this.i;
}
}

//定义为受保护的,外部访问收到限制
protected class PDestination implements Destination{
private String label;

//构造方法私有,外部不能直接new
private PDestination(String whereTo){
this.label = whereTo;
}

public String readLabel(){
return this.label;
}
}

//提供公共方法,用于返回接口类型内部实现
public Contents contents(){
return new PContents();
}

//提供公共方法,用于返回接口类型内部实现
public Destination destination(String dest){
return new PDestination(dest);
}

//程序入口
public static void main(String[] args) {
Parcel parcel = new Parcel();
Contents contents = parcel.contents();
Destination destination = parcel.destination("Singapore");

System.out.println(contents.value());
System.out.println(destination.readLabel());
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息