+1

Can we access private constructor of first class​ in second to create Object of first class?

Deep Java & Spring knowledge required

8/9/2019 9:40:22 PM

Nilesh Shinde

3 Answers

New Answer

+1

Possible by using reflection API and factory method

+3

Nilesh Shinde Everything / anything private belongs to class in which they are private, so it's not accessible from outside of class. Moreover if the constructor is private then that class object cannot be created in/by other classes. To create an object of class with private constructor, you need a public static method in the first class class PrivateC { private PrivateC() {} // private constructor public static PrivateC CreateObject() { return new PrivateC(); } public void Fun(){ System.out.println("Private"); } } Then in another class method or main or as member variable PrivateC pobj = PrivateC.CreateObject(); pobj.Func(); I have not tried but instance may be created using classloader or by reflection

+1

Ya it is possible by reflection api