Private, Abstract, Array And String Constructors In Java

This tutorial will discuss special constructors such as Private constructor in Java, Abstract, String, Array, Interface and Destructor in Java:

In our last tutorial on constructors in Java, we learned the important concepts related to constructors in Java. We discussed how to create a constructor and the rules to define constructors, along with the types of constructors, etc.

We also learned constructor overloading and constructor chaining. Now, let us discuss certain special constructors like a private constructor, abstract constructor, and string & array constructors in Java. Then we will discuss destructors in Java and finally, we will explore the differences between method and constructors.

=> Take A Look At The Java Beginners Guide Here.

Private & Abstract Constructors in Java

Let’s begin with a Private Constructor in Java.

Private Constructor In Java

As already mentioned, constructors in Java class can have access specifiers associated with them. Hence, we can have constructors that are private or public. We will discuss more on access specifiers in our subsequent tutorials and we will also revisit constructors once again.

When the constructor is declared private, then it can be accessed only inside the class. It cannot access the derived classes through another class. Hence we need to provide a public method in the class that has private constructors so that this public method can access the private constructors.

In Java private constructor can be used in the following situations:

  • For implementing singletons.
  • For incorporating factory methods.
  • For classes that have only static members (variables and methods).
  • For classes having final members. (constants – final and static).
  • To use type-safe enumerations.

As an example, let’s take a singleton class. A singleton class is a class that allows only one object at a time. We can use the private constructor to ensure that we do not allow more than one object to be created.

The below program implements a singleton class using a private constructor.

class SingleTonClass {
   //Static Class Reference
   private static SingleTonClass obj=null;
   private SingleTonClass(){
   System.out.println("SingleTonClass::Private constructor");
   }
   public static SingleTonClass create_object(){
	        //logic to create only one instance
		if(obj==null){
	    obj= new SingleTonClass();
	    }
   return obj;
   }
   public void display(){
	       System.out.println("This is SingleTonClass !!");
   }
}
class Main {
   public static void main(String args[]){
	    //cannot call private constructor directly.
	   SingleTonClass myobject= SingleTonClass.create_object();
	   myobject.display();
   }
}

Output:

Private constructor in Java

The above program declares a singleton class. We have provided a private constructor and a public method to access the private constructor and also to limit the number of objects to only one. In the main method, we execute the public method to create a singleton class object.

Abstract Class Constructor In Java

Abstract class in Java as C++ except that unlike C++, we have an abstract keyword in Java used to declare an abstract class. Abstract classes in Java can have constructors. This abstract class constructor is called when we create an instance of an implementation class (that inherits abstract class).

Consider the following example of an Abstract Class Constructor.

//abstract class declaration
abstract class BaseClass { 
    BaseClass() { System.out.println("BaseClass::Constructor Called"); } 
    abstract void func1(); 
} 
class DerivedClass extends BaseClass { 
    DerivedClass() { System.out.println("DerivedClass::Constructor Called"); } 
    void func1() { System.out.println("DerivedClass::func1() called"); } 
} 
class Main { 
    public static void main(String args[]) {  
       DerivedClass d = new DerivedClass(); 
    } 
}

Output:

Abstract class constructor in Java - output

As an abstract class cannot be instantiated, we inherit a new class from this abstract class. The output of the program shows that when we create an object of the derived class in the main method, then the constructor of the abstract class is called first, followed by a derived class constructor.

Interface Constructor In Java

Interfaces in Java are similar to abstract classes. Interfaces are by default public abstract and only have method prototypes. These prototypes are then implemented in the class that implements the interface.

So are constructors present in Interfaces?

No. Interfaces do not have constructors. This is because the methods in an interface are just prototypes and hence we need not instantiate or create an object of the interface as we are not going to use it at all. Hence there is no need to have a constructor in the interface either.

The below Java program demonstrates this logic.

//interface declaration
interface Interface_Add{    

public int addNumbers(int num1, int num2); //method prototype
}
class AddClass implements Interface_Add{
    public int addNumbers(int num1, int num2){  //method implementation
   int result= num1+num2;
   return result;
    }
}
class Main{
public static void main(String args[])
    {
 AddClass obj= new AddClass();
           
System.out.println("Result of addition:" + obj.addNumbers(2, 3));
    }
}

Output:

Interface constructor - output

Here, we have an interface ‘Interface_add’ with one method ‘addNumbers’ prototype. Then a class ‘AddClass’ implements this interface and also the method addNumbers.

In the main method, the class is instantiated and the method is executed. Hence we do not see any need for a constructor in this interface.

Now let’s discuss constructors of some preexisting classes in Java-like String and Array.

String Constructor In Java

A string object in Java can be defined as an object of class String. String class provides the following constructors to create and initialize String objects.

Some of these constructors are discussed below:

#1) String(byte[] myArray)

Constructs a new String object from a given byte array. For constructing the string object, it uses the default platform character set and decodes the byte array.

Example:

byte[] myArray = {65, 66, 67, 68, 69};
String str =new String(myArray); //ABCDE

#2) String(byte[] myArray, Charset char_set)

This constructor constructs a new string object by using char_set specified in the constructor call to decode the byte array.

Example:

byte[] myArray = {65, 66, 67, 68, 69};
Charset cs = Charset.defaultCharset();
String str = new String(myArray, cs); //ABCDE

#3) String(char[] myArray) 

We can construct a String object from a character array.

Example:

char myArray[] = {'P', 'a', 'r', 'i', 's'};
String s = new String(myArray); //Paris

#4) String(char[] myArray, int start_index, int count) 

Here, we construct a String object from character array by including the number of characters from start_index up to the count.

Example:

char myArray[] = {'P', 'a', 'r', 'i', 's'};
String s = new String(myArray, 0,2); //Pa

#5) String(int[] intArray, int offset, int count) 

The above constructor allocates a new String object from an int array. The number of characters in the string is defined by offset and count.

Example:

int[] intArray = {65, 69,73,79,85 };

String s = new String (intArray, 0, 5); //AEIOU

#6) String(StringBuffer strbuffer)

In this constructor, a new String object is constructed from a StringBuffer object.

Example:

StringBuffer strbuffer = new StringBuffer("SoftwareTestingHelp");

String s = new String (strbuffer); //SoftwareTestingHelp

#7) String(StringBuilder strbuilder)

A new String object is created using the StringBuilder object.

Example:

StringBuilder strbuilder = new StringBuilder("SoftwareTestingHelp");

String s = new String(strbuilder); // SoftwareTestingHelp

Array Constructors In Java

Arrays use constructors to create and initialize arrays using a new keyword as shown below.

int[] data = new int[4];

The above statement initializes an array of 4 elements to default 0.

Another way of initializing the array is given below:

int[] data = new int[]{2, 4, 6, 8};

Destructor In Java

So far we have seen constructors in Java using which we create an object. When the object has finished with its job and is no longer required, then the memory allocated to the object needs to be released or deallocated. This is the job of a destructor in Java.

In Java, the Garbage Collector is responsible for releasing the objects that are no more in use or have become unreachable. Destructors in Java are called finalizers and they are non-deterministic such that we cannot guarantee that they will be executed.

In Java, we need not worry about destructors. Destructors do not have a specific syntax in Java. Objects are destroyed but we do not call destructor in the way we call it in C++.

As mentioned above, the job of the destructor is done by the finalizer which is called by the Garbage Collector.

The finalizer method in Java is demonstrated below for your reference.

class Main
{
    public static void main(String[] args)
    {   
        Main dm = new Main();       //create object
        dm = null;
        System.gc();                //call garbage collector
        System.out.println("Main Mathod");  
    }
    protected void finalize()       //finalize method
    {
        System.out.println("Finalize method :: object is garbage collected");
    }
}

Output:

Destructor in Java

In the above program, we create a class object. Set it to null and then we call System.gc () method. Now that object is unreachable, and the finalize method (destructor) is implicitly called.

Constructor Vs Method In Java

Let’s tabularize some of the differences between a Constructor and a Method in Java.

ConstructorsMethod
A block of code used to initialize the class members when creating an object.A collection of programming statements that generate a result when executed.
Used to perform initialization of objects.A sequence of statements that are executed by Java. May or may not contain an initialization routine.
Invoked implicitly.Needs to be invoked explicitly in a program.
Invoked when a new object is created using the new keyword.Invoked when the method is called by the programmer.
Has the same name as that of a class.It can have any name permitted by programming language.
Doesn’t have a return type.Must have return type or else it should return void.
Creates a new object.Operates on an already existing object.
A class can have many overloaded constructors.The class can have overloaded as well as distinct methods.
It cannot be inherited by the child class.It can be inherited by child class and even overridden.

Frequently Asked Questions

Q #1) Can Constructors be Private?

Answer: Yes. Constructors in Java can be private. All classes including abstract classes can have private constructors. Using private constructors we can prevent the class from being instantiated or we can limit the number of objects of that class.

Q #2) What is the use of Abstract Class Constructor in Java?

Answer: An abstract class constructor is invoked when we create an object of the derived class that inherits the abstract class. Besides if the abstract class has some member variables, we can initialize them in the abstract class constructor.

Q #3) Can we define a Parameterized Constructor in an Abstract class in Java?

Answer: Yes, we can have a parameterized constructor in an abstract class. Then we can call this constructor from the derived class that inherited the abstract class using super () call.

Q #4) Do you know why there is no Destructor in Java?

Answer: Java need not have a specific destructor as it has its garbage collector. This garbage collector destroys the objects that are unreachable and releases the memory. A method named finalize is also a part of the garbage collector that executes non-deterministically and performs the function of destructor like freeing the resources etc.

Q #5) Can Abstract Class have a body?

Answer: No. An abstract class can only have method declarations and constructors. Its methods are not implemented. The class that inherits this abstract class implements the methods. Apart from prototype or declarations, it can also have visibility or access specifiers.

Conclusion

This completes our tutorial on constructors in Java. Here, we have covered the definition, creation, and types of constructors. We also discussed constructor overloading and constructor chaining in Java.

We explored abstract and private constructors in Java and learned why interfaces cannot have constructors. We saw constructors that are used in array and String classes.

We also discussed destructors in Java that perform the function opposite to that of constructors. Constructors create objects while destructors destroy objects. In Java, the destructor function is carried out by the finalizer which is executed during garbage collection.

Thus, we do not have a specific destructor in Java and we need not define it in the way we do in C++. We also discussed the differences between method and constructor. We know that constructor is not the same as a method but we can view constructor as a special method.

=> Read Through The Easy Java Training Series.