Way2Java

Can you make Private Constructor in Java?

Declaring a private constructor is a very rare usage. First of all can we do it?

Yes, a constructor can be private and a private constructor can be overloaded also.

Following program illustrates.

public class Test
{
  private Test()
  {
    System.out.println("I am default private constructor");
  }
  private Test(int x)
  {
    System.out.println("I am overloaded private constructor. " +x);
  }
  public static void main(String args[])
  {         
    Test t1 = new Test();
    Test t2 = new Test(10);
  }
}

In the above program, Test class created two private constructors – default and overloaded with int parameter. Program works nice. Observe the above screenshot.

Then, what is the use of declaring a constructor private?

Programmer can achieve two functionalities with a private constructor.

1. Composition (or has-a relationship) is not possible with default constructor. That is, you cannot create an object of the class in another class with default constructor.
2. The class with private constructor is not fit for inheritance. That is, the class cannot be extended.

The above two statements are proved programmatically hereunder.

1. Composition is not possible

In the following code, Test class includes a private default constructor.

class Test
{
  private Test()
  {
    System.out.println("I am default private constructor");
  }
}
public class Demo
{
  public static void main(String args[])
  {         
    Test t1 = new Test();
  }
}

The Demo class cannot create an object of Test in its main() method. Observe the screenshot about the compiler message. If the constructor is not private, the Demo can do it within no time as usual.

2. Not fit for inheritance

The class with private constructor cannot be extended. Observe the following code.

public class Test
{
  private Test()
  {
    System.out.println("I am default private constructor");
  }
}
public class Demo extends Test
{
  public static void main(String args[])
  {
    Demo d1 = new Demo();
  }
}

The above program raises compilation error. Why? We know a subclass constructor class super class constructor implicitly.

Demo d1 = new Demo();

The subclass Demo() constructor calls super class Test() constructor implicitly. But it cannot as Test() constructor has private access. For this reason, Test() cannot be extended by any other class,

Can you make class not to be extended by another without declaring it final?

Yes, simple, declare the constructor as private.

What other access modifiers a constructor cannot be?

"A constructor cannot be abstract, static, final, native, strictfp, or synchronized". Explained clearly in Java Constructor Properties