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条回答
forever°为你锁心
2楼-- · 2019-03-08 03:27

There is no rule that constructor to be public .Generally we define it public just because we would like to instantiate it from other classes too .

Private constructor means,"i dont let anyone create my instance except me ". So normally you would do this when you like to have a singleton pattern.

Following is the class in JDK which uses a private constructor .

public class Runtime {
    private static Runtime currentRuntime = new Runtime();

    public static Runtime getRuntime() {
        return currentRuntime;
    }

    // Don't let anyone else instantiate this class
    private Runtime() {
    }
}
查看更多
叼着烟拽天下
3楼-- · 2019-03-08 03:27

A constructor has to be at least protected or even private while creating, for example, custom factory classes, like:

public final class MyFactory {
  private MyFactory(){} // this one prevents instances of your factory
}

public static void doSomething(){} // access that with MyFactory.doSomething

Note that this is only one example showing when a constructor shouldn't be public.

查看更多
地球回转人心会变
4楼-- · 2019-03-08 03:31

Others have noted that constructors may have access modifiers; an aspect not yet mentioned is that the aspect modifiers on a constructor control two very different aspects of construction, but do not allow them to be controlled separately:

  1. Who is allowed to create instances of ClassName and what constructors are they allowed to use.
  2. Who is allowed to create extensions of ClassName and what constructors are they allowed to use.

Both Java and .NET require that the answers to those two questions go together; if a class isn't final (or sealed) and allows a constructor to be used by outside code to create new instances, then outside code will also have total freedom to use that same constructor to create derived types.

In many cases, it may be appropriate for a class to have only package-private (internal) constructors, but expose public methods that return new instances. Such an approach might be used if one were designing a type like String from scratch; a package including String could define it as an abstract type but include concrete derived types like AsciiString and UCS16String which store their content as a byte[] and Char[], respectively; methods that return String could then return one of the derivatives depending upon whether the string contained characters outside the ASCII range. If neither String nor any derived types expose any constructors outside its package, and all derived types within the package behave as a string would be expected to behave, then code which receives a reference of type String could expect it to behave sanely as a string (e.g. guaranteeing that any observations about its value will forevermore remain true). Exposing constructors outside the package, however, would make it possible for derived types to behave in weird and bizarre fashion (e.g. changing their contents after they've been examined and validated).

From a syntactical perspective, being able to say Fnord foo = new Fnord(123); is a little nicer than having to say Fnord foo = Fnord.Create(123);, but a class Fnord that requires the latter syntax can maintain much better control over the object-creation process.

查看更多
贼婆χ
5楼-- · 2019-03-08 03:37

The simple explanation is if there is no constructor in a class, the compiler automatically creates a default constructor.

The constructor is not always declared as public, it can also be private, protected, or default.

The private constructors prevent a class from fully and clearly expressed/represented by its callers. In that case private constructors are useful. And if if we do not need our class to be sub-classed, we can use private constructors.

查看更多
狗以群分
6楼-- · 2019-03-08 03:39

I agree with the previous answers that a Singleton is a good example of a class having a private constructor. I would though recommend a different implementation: a thread safe Singleton:

/**
 * Thread safe singleton
 */
public class Singleton {

    private static volatile Singleton instance = null;

    /**
     * Private constructor
     */
    private Singleton() {
    }

    /**
     * Gets the Instance of the Singleton in a thread safe way.
     * @return
     */
    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

Using a singleton in a thread safe way will safe you a lot of pain in parallel code.

查看更多
倾城 Initia
7楼-- · 2019-03-08 03:39

Most of these answers refer to a singleton or factory class. Another time a private constructor appears is (for example) in the java.lang.Math class, where everything is static and no one should ever call the constructor (including the class itself). By having the private constructor, you prevent anyone outside the class from calling the constructor. (This doesn’t prevent someone inside the class from calling the constructor, but then they’re breaking their own rule.)

查看更多
登录 后发表回答