How can we create objects if we make the constructor private ?



How can we create objects if we make the constructor private ?..

Answer / Prachi Sachan

To create objects when a constructor is made private, you can use one of two methods: Static Factory Methods or Inner classes.
1. Static Factory Method: A static method in the class can be used to create and return an instance of the class. The advantage is that it does not violate the encapsulation because the constructor is private.
2. Inner Classes: You can declare a non-static inner class, which has access to the private constructor of the outer class, and use that to create an instance. This also maintains encapsulation.

Is This Answer Correct ?    0 Yes 0 No

Post New Answer

More Core Java Interview Questions

Can inner class extend any class?

1 Answers  


Explain the differences between abstraction and encapsulation?

1 Answers  


Can we declare variables inside a method as Final Variables?

3 Answers  


What technique is carried out to find out if a particular string is empty?

1 Answers  


Difference between character constant and string constant in java ?

1 Answers  


Is hashset ordered java?

1 Answers  


What are library required to connect to excel sheet.

2 Answers   Cap Gemini,


IS method overriding is Duplication of Methods?

5 Answers   CybAge,


can u handle an error if u write Thowable in the catch class lise try { some errorneous code }catch(Throwable e){ ...}

4 Answers  


Under what conditions is an object’s finalize() method invoked by the garbage collector?

1 Answers  


relation between list and linked list

1 Answers   Infosys,


What is the locale class in java programming?

1 Answers  


Categories