14.1 In terms of inheritance, what is the effect of keeping a constructor private? 这道题问我们用继承特性时,如果建立一个私有的构建函数会怎样. 只有能访问该函数的私有变量或函数的东西才能访问私有构建函数,比如内部类就可以访问,比如类A是类Q的一个内部类,那么Q的其他内部类可以访问类A的私有构建函数. 由于一个子类可以调用父类的构建函数,类A可以被继承,所以只有类A的子类或者是类Q的其他子类可以访问类A的私有构建函…
14.5 Explain what object reflection is in Java and why it is useful. Java中的对象反射机制可以获得Java类和对象的反射信息,并可采取如下操作: 1. 在运行阶段获得类内部的方法和字段信息 2. 新建类的实例 3.通过获取字段引用来获得和舍弃对象字段,无论该字段是私有还是公有的. 下列代码是对象反射的一个例子: // Parameters Object[] doubleArgs = new Object[] {4.2, 3.…
A private constructor is a special instance constructor. It is generally used in classes that contain static members only. If a class has one or more private constructors and no public constructors, other classes (except nested classes) cannot create…
Principle When implement the singleton pattern please decorate the INSTANCE field with "static final" and decorate the constructor with "private". // Singleton with static factory public class Elvis { private static final Elvis INSTANC…
A class can be made noninstantiable by including a private constructor. // Noninstantiable utility class public class UtilityClass { // Suppress default constructor for noninstantiability private UtilityClass() { throw new AssertionError(); } ... //…
Item4:Enforce noninstantiability with a private constructor 通过构造私有化,禁止对象被实例化. public class UtilClass { private UtilClass(){ //防止类内的函数调用构造函数创建对象 throw new AssertionError(); } }…
Item3:Enforce the singleton property with a private constructor or an enum type 采用枚举类型(ENUM)实现单例模式. public enum Elvis { INSTANCE; public void leaveTheBuiding(){ System.out.println("a single-element enum type is the best way to implement a singleton&q…