Do you always need to publish constructors?

My first question is

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

Should Constructor be declared publicly available?

What if I create a private constructor.

I have always seen constructors implicitly public . So why is the private constructor useful? Or it is not useful at all. Because no one could ever call it or never create an object (because of the private constructor)! And this is my second question.

+44
java access-modifiers constructor oop object-lifetime
Jun 23 '15 at 7:02
source share
11 answers

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

Creating something private does not mean that no one can access it. It just means that no one outside the class can access it. Therefore, the private constructor is also useful.

One use of the private constructor is to use singleton classes. The singleton class is the one that limits the amount of object creation to one. Using the private constructor, we can guarantee 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; } } 

Additional information on access modifiers.

+64
Jun 23 '15 at 7:03
source share

Yes, constructors can have some kind of access modifier / modifier.

Private constructors are useful for creating singleton classes.

Singleton The singleton class is a class in which only one 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 that for the above class, the only way to get an object (outside this class) is to call the getInstance () function, which will create only one instance and save it.

Also, please note that this is not thread safe.

+9
Jun 23 '15 at 7:08
source share

Designers can be public, standard, or private, and it all depends on what you want to do with it.

For example, if you define a Singleton class, you better hide (which makes it private so that it is accessible only to the class where it belongs) the constructor to prevent other classes from creating your own class.

You might want to declare it by default, for example, for testing purposes, so that test cases in one package can access it.

More information can be found here.

+6
Jun 23 '15 at 7:11
source share

There is no rule that the constructor is publicly available. In fact, we define it public only because we want to create it from other classes as well.

Private constructor means: "I do not allow anyone to create my instance except me." So usually you do this when you like to have a singleton pattern.

The following is a class in the JDK that 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() { } } 
+5
Jun 23 '15 at 7:20
source share

No, designers can use any access modifier, including private. (A personal constructor means that only code inside the class itself can instantiate an object of this type, therefore, if a 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 the instance created inside 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); } } 

The output of the above program will be

alpha subsub

+5
Jun 23 '15 at 7:46
source share

Constructors can have all kinds of access modifiers. The use of different access modifiers in the constructors is different.

You create a public constructor if you want the class to be created from anywhere.

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

You create a private constructor if you want the class to be created only from its own elements, usually a static block or a static method. This means that you take control of the instance of the class and apply some rule to the instance. An example of using a private constructor is a singleton design template.

+4
Jun 23 '15 at 7:14
source share

I agree with the previous answers that Singleton is a good example of a class that has a private constructor. I would recommend another implementation: 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 thread in a safe thread will help you avoid the pain of parallel code.

+4
Jun 23 '15 at 7:54
source share

The constructor has at least protected or even closed when creating, for example, custom factory classes, such as:

 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 just one example showing when the constructor should not be publicly available.

+3
Jun 23 '15 at 7:19
source share

Most of these answers are in the singleton or factory class. Another time, when a private constructor appears (for example), in the java.lang.Math class , where everything is static and no one should ever call the constructor (including the class itself). Having a private constructor, you forbid anyone other than the class to call the constructor. (This does not stop anyone from calling the constructor, but then they break their own rule.)

+1
Jun 23 '15 at 16:16
source share

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

  • Who is allowed to instantiate ClassName and which constructors are allowed to use them.
  • Who is allowed to create ClassName extensions and which constructors are allowed to use them.

Both Java and .NET require that the answers to these two questions match; if the class is not final (or sealed ) and allows the constructor to use external code to create new instances, then the external code will also have complete freedom to use the same constructor to create derived types.

In many cases, it may be appropriate for the class to have only package-private ( internal ) constructors, but to expose public methods that return new instances. This approach can be used if you are developing a type such as String from scratch; a package that includes String can define it as an abstract type, but includes specific derived types, such as AsciiString and UCS16String , which store their contents as byte[] and Char[] respectively; methods that return String can then return one of the derivatives, depending on whether the strings contain characters outside the ASCII range. If neither String nor any derived types expose any constructors outside their package, and all derived types inside the package will behave like a string, they are expected to behave, then code that receives a reference of type String can expect it to be behave wisely as a string (for example, ensuring that any observation of its value remains true forever). However, using constructors outside the package would allow derived types to behave in a strange and bizarre way (for example, changing their contents after they have been validated and validated).

From a syntactic point of view, the ability to say Fnord foo = new Fnord(123); a little nicer than saying Fnord foo = Fnord.Create(123); , but the Fnord class, which requires the latest syntax, can significantly improve control over the process of creating an object.

+1
Jun 23 '15 at 17:19
source share

A simple explanation is the lack of a constructor in the class, the compiler automatically creates a default constructor.

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

Private constructors do not allow the class to be fully and clearly expressed / represented by its callers. Private constructors are useful in this case. And if we do not need our class to subclass, we can use private constructors.

0
Jun 23 '15 at 11:08
source share



All Articles