Do constructors always have to be public? [duplica

2019-03-08 02:54发布

This question already has an answer here:

My first question is -

   class Explain() {
        public Explain() {
      }
   }

Should Constructor always declared as public?

What if I create a private constructor.

I always seen constructors are implicitly public. So why private constructor is useful? Or is it not useful at all. Because nobody could ever call it, or never make an object(because of the private constructor) ! And that is my second question.

11条回答
做自己的国王
2楼-- · 2019-03-08 03:42

No,Constructors can use any access modifier, including private. (A private constructor means only code within the class itself can instantiate an object of that type, so if the private constructor class wants to allow an instance of the class to be used, the class must provide a static method or variable that allows access to an instance created from within the class.)

Example

class Alpha {
   static String s = " ";
   protected Alpha() { s += "alpha "; }
 }
 class SubAlpha extends Alpha {
   private SubAlpha() { s += "sub "; }
 }
 public class SubSubAlpha extends Alpha {
   private SubSubAlpha() { s += "subsub "; }
   public static void main(String[] args) {
     new SubSubAlpha();
     System.out.println(s);
   }
 }

Output of above program will be

alpha subsub

查看更多
冷血范
3楼-- · 2019-03-08 03:44

No, Constructors can be public, private, protected or default(no access modifier at all).

Making something private doesn't mean nobody can access it. It just means that nobody outside the class can access it. So private constructor is useful too.

One of the use of private constructor is to serve singleton classes. A singleton class is one which limits the number of objects creation to one. Using private constructor we can ensure that no more than one object can be created at a time.

Example -

public class Database {

    private static Database singleObject;
    private int record;
    private String name;

    private Database(String n) {
        name = n;
        record = 0;
    }

    public static synchronized Database getInstance(String n) {
        if (singleObject == null) {
            singleObject = new Database(n);
        }

        return singleObject;
    }

    public void doSomething() {
        System.out.println("Hello StackOverflow.");
    }

    public String getName() {
        return name;
    }
}

More information about access modifiers.

查看更多
Root(大扎)
4楼-- · 2019-03-08 03:45

Constructors can have all kind of access modifiers. The usage of different access modifier on constructors are different.

You make a constructor public if you want the class to be instantiated from any where.

You make a constructor protected if you want the class to be inherited and its inherited classes be instantiated.

You make a constructor private if you want the class to be instantiated just from its own members usually a static block or static method. It means that you take control of instantiating the class and apply some rule on instantiation. Example of usage of private constructor is singleton design pattern.

查看更多
放荡不羁爱自由
5楼-- · 2019-03-08 03:47

Yes , Constructors can have any access specifier/access modifier.

Private constructors are useful for creating singleton classes.

Singleton - A singleton class is a class where only a single object can be created at runtime (per JVM) .

A simple example of a singleton class is -

class Ex {
    private static Ex instance;
    int a;
    private Ex() {
        a = 10;
    }
    public static Ex getInstance() {
        if(instance == null) {
            instance = new Ex();
        }
        return instance;
    }
}

Note, for the above class, the only way to get an object (outside this class) is to call the getInstance() function, which would only create a single instance and keep returning that.

Also, note that this is not thread-safe.

查看更多
不美不萌又怎样
6楼-- · 2019-03-08 03:51

Constructors could be public, default or private and it all depends on what you want to do with it.

For example, if you are defining a Singleton class, you'd better hide (meaning making it private so that it is only available to the class where it belongs) the constructor to prevent other classes to instantiate your class at their will.

You may want to declare it default, let's say, for testing purposes so that test cases within the same package could access it.

More detailed info could be found here

查看更多
登录 后发表回答