Java — private constructor vs final and more

China☆狼群 提交于 2019-11-28 13:40:41

A class with private constructors cannot be instantiated except form inside that same class. This make it useless (possible, but will not compile) to extend it from antoher class.

This does not mean it cannot be subclassed at all, for example among inner classes you can extend and call the private constructor.

You declare a class final vs. make its constructor private for different reasons:

  • You make class final to indicate that the class is not designed for inheritance.
  • You make all constructors private to give the class the control over its instantiation.

In other words, using final controls inheritance, while using private constructors control instantiation.

Note that declaring constructors private disables inheritance only from the outside. Inside the class, you may still inherit it with a named or an anonymous derived class.

When you make all constructors of the class private you need a static method that is public to make the class usable. One common kind of the static method is factory method: you can let the users of your class call private constructors indirectly through a public static method.

From what I know the general use of a private constructor is to ensure that object construction is done via some other means, i.e. a static method. For example:

public class Something {

    private Something() { }

    public static Something createSomething() {
        Something ret = new Something();
        // configure ret in some specific way
        return ret;
    }

}

So a private constructor restricts how a class is instantiated (not how it is extended).

On the other hand, marking a class as final is used to explicitly say that a class cannot be extended. How it get's instantiated is a different matter entirely.

So while I'm not 100% if there is some way to extend a class that has all private constructors - the question is why do you want to do that? Having a private constructor and marking a class as final have two different purposes.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!