这是《JAVA编程思想》上的一个例子

解决方案 »

  1.   

    这样很正常啊,就是不对外嘛。你可看一下Singleton模式,我的类你就不能随便创建对象了。
      

  2.   

    你抄错了吧
    应该这样:
    public class Parcel4 {
        class PDestination{
            //implements Destination {
          private String label;
          private PDestination(String whereTo) {//˽Óй¹Ô캯Êý
            label = whereTo;
          }
          public String readLabel() { return label; }
        }
        
        public PDestination dest(String s) {
        return new PDestination(s);//ÓÃ˽Óй¹Ô캯Êý¹¹Ôì¶ÔÏ󣿣¿£¿ÎªÊ²Ã´¿ÉÒÔÕâÑù£¿£¿£¿
         }
      public static void main(String[] args) {
        Parcel4 p = new Parcel4();
        PDestination d = p.dest("Tanzania");
      }
    }
    此时PDestination是个内部类,它的私有方法是允许被Parcel4调用的如果这样:
    public class Parcel4 {
     
        
        
        public PDestination dest(String s) {
        return new PDestination(s);//ÓÃ˽Óй¹Ô캯Êý¹¹Ôì¶ÔÏ󣿣¿£¿ÎªÊ²Ã´¿ÉÒÔÕâÑù£¿£¿£¿
         }
      public static void main(String[] args) {
        Parcel4 p = new Parcel4();
        PDestination d = p.dest("Tanzania");
      }
    }class PDestination{
            //implements Destination {
          private String label;
          private PDestination(String whereTo) {//˽Óй¹Ô캯Êý
            label = whereTo;
          }
          public String readLabel() { return label; }
    }
    即PDestination定义在外面
    就不可以调用私有构造函数了
      

  3.   

    和 单态 Singleton 差不多,应该不是 Singleton,如果是Singleton的话,只能创建一个对象,因为有static 和final 限制。不过 私有构造函数 的目的也是 为了防止随便创建对象,这样你如果写这样的程序,只有你了解你的程序的实现原理,你知道怎么去创建一个对象,别人不知道,也就不可以随便的创建对象。