Java — private constructor vs final and more

前端 未结 3 772
轮回少年
轮回少年 2020-12-10 16:11

Suppose there is a class with all of its constructors declared as private.

Eg.:

public class This {
    private This () { }

    public someMethod(          


        
3条回答
  •  旧巷少年郎
    2020-12-10 16:45

    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.

提交回复
热议问题