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?
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.
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.
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.
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!"; } }
It's not really clear if any of these apply though - can you give more information?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With