Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access a private constructor of a class?

I am a Java developer. In an interview I was asked a question about private constructors:

Can you access a private constructor of a class and instantiate it?

I answered 'No' but was wrong.

Can you explain why I was wrong and give an example of instantiating an object with a private constructor?

like image 600
gmhk Avatar asked Apr 08 '10 11:04

gmhk


People also ask

Can we call private constructor?

Yes, we can declare a constructor as private. If we declare a constructor as private we are not able to create an object of a class. We can use this private constructor in the Singleton Design Pattern.

How can you use a private constructor?

Private constructors are used to prevent creating instances of a class when there are no instance fields or methods, such as the Math class, or when a method is called to obtain an instance of a class. If all the methods in the class are static, consider making the complete class static.

Can access object of class have private constructor?

Yes, we can access the private constructor or instantiate a class with private constructor. The java reflection API and the singleton design pattern has heavily utilized concept to access to private constructor.


2 Answers

One way to bypass the restriction is to use reflections:

import java.lang.reflect.Constructor;  public class Example {     public static void main(final String[] args) throws Exception {         Constructor<Foo> constructor = Foo.class.getDeclaredConstructor();         constructor.setAccessible(true);         Foo foo = constructor.newInstance();         System.out.println(foo);     } }  class Foo {     private Foo() {         // private!     }      @Override     public String toString() {         return "I'm a Foo and I'm alright!";     } } 
like image 55
Joachim Sauer Avatar answered Oct 21 '22 17:10

Joachim Sauer


  • You can access it within the class itself (e.g. in a public static factory method)
  • If it's a nested class, you can access it from the enclosing class
  • Subject to appropriate permissions, you can access it with reflection

It's not really clear if any of these apply though - can you give more information?

like image 28
Jon Skeet Avatar answered Oct 21 '22 16:10

Jon Skeet