最近在阅读JAVA编程思想这本书的时候,看到第十章内部类时,碰到一个小问题,求高手解疑释惑。
先源代码
public class Parcel2
{
class Contents{
private int i=11;
public int value(){
return i;
}
}
class Destination{
private String label;
Destination(String whereTo){
label=whereTo;
}
String readLabel(){
return label;
}
}
public Destination to(String s){
return new Destination(s);
}
public Contents contents(){
return new Contents();
}
public void ship(String dest){
Contents c=contents();
//Parcel2.Contents c1=contents();
Destination d=to(dest);
System.out.println(d.readLabel());
}
/**
 * @param args
 */
public static void main(String[] args) {
Parcel2 p=new Parcel2();
p.ship("Tasmania");
Parcel2 q=new Parcel2();
Parcel2.Contents c=q.contents();
Parcel2.Destination d=q.to("Borneo");
}}
原著上说,如果想从外部类的非静态方法之外的任意位置创建某个内部的对象,
那么必须像在main()方法中那样,具体指明这个对象的类型:OuterClassName.InnerClassName
具体表现就是Parcel2.Contents c=q.contents();Parcel2.Destination d=q.to("Borneo");问题来了,我在main方法中增加Contents c1=q.contents();代码,也没有具体指定外部类的类名,编译器也通过了,也可以正常运行。那原著中说所提到的这个必须是什么意思呢?实在不明白。