private知识笔记

下面是应用了private的一个例子:


    //: IceCream.java
    // Demonstrates "private" keyword

    class Sundae {
      private Sundae() {}
      static Sundae makeASundae() { 
        return new Sundae(); 
      }
    }

    public class IceCream {
      public static void main(String[] args) {
        //! Sundae x = new Sundae();
        Sundae x = Sundae.makeASundae();
      }
    } ///:~
View Code


这个例子向我们证明了使用private的方便:有时可能想控制对象的创建方式,并防止有人直接访问一个特定的构建器(或者所有构建器)。在上面的例子中,我们不可通过它的构建器创建一个Sundae对象;相反,必须调用makeASundae()方法来实现(注释③)。

③:此时还会产生另一个影响:由于默认构建器是唯一获得定义的,而且它的属性是private,所以可防止对这个类的继承(这是第6章要重点讲述的主题)。

--《Think in java》5.2.3

原文地址:https://www.cnblogs.com/fanmzdj/p/3405057.html