主要是关于下面这段代码的解释,其中一个地方完全无法理解
class Parcel4 {
private class PContents implements Contents {
private int i = 11;
public int value() { return i; }
}
protected class PDestination implements Destination {
private String label;
private PDestination(String whereTo) {
label = whereTo;
}
public String readLabel() { return label; }
}
public Destination destination(String s) {
return new PDestination(s);
}
public Contents contents() {
return new PContents();
}
}public class TestParcel {
public static void main(String[] args) {
Parcel4 p = new Parcel4();
Contents c = p.contents();
Destination d = p.destination("Tasmania");
// Illegal -- can't access private class:
Parcel4.PDestination pc = p.new PDestination();
}
} 下面是截取书中原话"PDestination是protected , 所以只有Parcel4及其子类、还有与Parcel4同一个包中的类能访问PDestination,其他类都不能访问PDestination。这意味着,如果客户端程序员想了解或访问这些成员,那是要受到限制的。实际上,甚至不能向下转型成private内部类(或protected内部类,除非是继承自它的子类),因为不能访问其名字,就像在TestParcel类中看到的那样。"
上面红色字体部分就是我无法理解的部分,还请各位高手解答~~
class Parcel4 {
private class PContents implements Contents {
private int i = 11;
public int value() { return i; }
}
protected class PDestination implements Destination {
private String label;
private PDestination(String whereTo) {
label = whereTo;
}
public String readLabel() { return label; }
}
public Destination destination(String s) {
return new PDestination(s);
}
public Contents contents() {
return new PContents();
}
}public class TestParcel {
public static void main(String[] args) {
Parcel4 p = new Parcel4();
Contents c = p.contents();
Destination d = p.destination("Tasmania");
// Illegal -- can't access private class:
Parcel4.PDestination pc = p.new PDestination();
}
} 下面是截取书中原话"PDestination是protected , 所以只有Parcel4及其子类、还有与Parcel4同一个包中的类能访问PDestination,其他类都不能访问PDestination。这意味着,如果客户端程序员想了解或访问这些成员,那是要受到限制的。实际上,甚至不能向下转型成private内部类(或protected内部类,除非是继承自它的子类),因为不能访问其名字,就像在TestParcel类中看到的那样。"
上面红色字体部分就是我无法理解的部分,还请各位高手解答~~
楼主【llm0528】截止到2008-07-27 22:23:50的历史汇总数据(不包括此帖):
发帖的总数量:62 发帖的总分数:1280 每贴平均分数:20
回帖的总数量:54 得分贴总数量:0 回帖的得分率:0%
结贴的总数量:62 结贴的总分数:1280
无满意结贴数:0 无满意结贴分:0
未结的帖子数:0 未结的总分数:0
结贴的百分比:100.00% 结分的百分比:100.00%
无满意结贴率:0.00 % 无满意结分率:0.00 %
敬礼!
比如
Object obj=new String("abc");
因为我们知道这个obj实际指向的是String对象。所以我们可以这样向下转型:
String str=(String)obj;而这个例子中,
Contents c = p.contents();
我们指知道Contents是个接口类型,c指向了一个实现了这个接口的类的对象。但至于这个类是什么我们就不知道了。所以不能指向向下转换。
2、(或protected内部类,除非是继承自它的子类) 这句更加摸不着头脑了...
也就是说下面这句是不可以的:
Parcel4.PContents d=(Parcel4.Pcontents)c;
因为你不知道Parcel4.PContents这个了类型的存在,更不用说类型转换了对于Protected:
Destination d = p.destination("Tasmania");
// Illegal -- can't access private class:
Parcel4.PDestination pc = (Parcel4.PDestination)d;
也是不可以的。如果你让例子中的TestParcel类继承Parcel4,就可以执行上面这句话,因为Parcel4.PDestination是protected的,在子类中可以看到这个内部类定义。
自己改代码看看。