-1

I want to create object of Base class in another class but Base class constructor is defined as private

Here is my Code

public class Main
{
  public static void main(String ... args)
  {
    //Base objBase = new Base();
    //objBase.show();
  }
}


class Base
{
  private Base()
  {

  }

  public void show()
  {
     System.out.println("Base Class Show() Method");
  }
}
Kiran Choudhary
  • 1,125
  • 7
  • 15
  • 1
    You can't. That's why you make constructors private. – Emil Laine Mar 25 '15 at 06:21
  • You could try reflection. But unless you are answering a interview question, then the best way would be to modify this code – Scary Wombat Mar 25 '15 at 06:21
  • You can use reflection, but that defeats the purpose of having it private. – Bathsheba Mar 25 '15 at 06:21
  • If that is your class, you can add a `static` factory method, to return the instance, or even make the constructor `non-private`. If it's not your class, then there is something wrong with the person who created it, if he hasn't given any way. May be you're not supposed to create it's instance? – Rohit Jain Mar 25 '15 at 06:21
  • 2
    The reason it's private is likely because it needs to be constructed via some kind of builder of factory – MadProgrammer Mar 25 '15 at 06:21
  • May be it is duplicate of http://stackoverflow.com/questions/23871173/how-to-create-objects-from-a-class-with-private-constructor?rq=1 and http://stackoverflow.com/questions/2599440/how-can-i-access-a-private-constructor-of-a-class?rq=1 – Unknown Mar 25 '15 at 06:25
  • @MadProgrammer - Or because it is supposed to be a *Singleton* :P – TheLostMind Mar 25 '15 at 06:31

2 Answers2

4

Code inside Base is still allowed to call the constructor, which means it's possible to create objects in a static method:

class Base
{
  private Base()
  {

  }

  public void show()
  {
     System.out.println("Base Class Show() Method");
  }

  public static Base createBase() {
      return new Base();
  }
}

and then call the method to create an object:

Base objBase = Base.createBase();
objBase.show();
user253751
  • 57,427
  • 7
  • 48
  • 90
1

You cannot create objects of classes if they have private constructors. Objects can be constructed, but only internally. That is how it is.

There are some common cases where a private constructor can be useful:

  1. Singletons
  2. Classes containing only static methods
  3. Classes containing only constants
  4. Type safe enumerations

Hoping this helps.

spiralarchitect
  • 880
  • 7
  • 19
  • Plus, there are people who think factory methods are more readable than constructors. If a class has more than one constructor, you can give factory methods different, descriptive names, and you can't do that with constructors. – ajb Mar 25 '15 at 06:36