简体   繁体   中英

Static Factory methods

As per Joshu Bloch's Effective Java,"The main disadvantage of providing only static factory methods is that classes without public or protected constructors cannot be subclassed." Can someone please explain what does this mean? Especially the bolded words. If a static factory method is provided or not, class with private constructor can't be subclassed right?

Providing only static factory methods is that classes without public or protected constructors cannot be subclassed.

Whenever a constructor of a subclass is called, the constructor of the parent class is also called. In the absence of protected or public constructors, sub classing or extending a class will make no sense. Hence the disadvantage.

Java requires from derived class to ensure that inherited fields will be properly initialized. It is done by making at start of constructor call to constructor of superclass.

Such code should look like

class Derived class Parent{
    public Derived(){
        super();//this will be added automatically by compiler
        //or super(arguments) if you want to use constructor with arguments
    }
}

But if superclass doesn't make its constructor accessible (it is privet) derived class can't add super call in any of its constructor. This means that we can't create valid code for constructor, and since all classes must have at least one constructors derived class can't compile.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM