+ 9
A question from a challenge on 11/11/17
Can anyone explain this code, please? I've checked the answer and I know it now. But I want you to tell me to confirm that you know. And please explain if there's a problem to use "private" keyword with a constructor? Why (String...args) but not []? What is the output of the following code? class A { public A() {System.out.print("hello"); } } class B { private B() {System.out.print("world"); } } public class Main { public static void main (String...args) { A a = new A(); B b = new B(); } }
3 Answers
+ 4
The ... is used for a variadic parameter/argument. It is for use with an unknown or variable amount of parameters of the given type. It is essentially an array and is being used in place of the usual String[] args here.
Yes, you can have a private constructor, but you can't call that private constructor using the new keyword like you would to create any other object. private constructors are most commonly used with the Singleton data structure.
+ 8
I don't understand what "Singleton data structure" is
+ 5
The singleton data structure or singleton design pattern, is a class that is created in such a way that only 1 instantiated object of that class will exist at any given time throughout the current lifecycle of a running program so that it will be shared acrossed all uses within the program.
https://www.google.com/amp/s/www.journaldev.com/1377/java-singleton-design-pattern-best-practices-examples/amp