Constructor overloading with static block in Java


The act of instantiating an object calls forth its corresponding constructor underpinning much of the functionality present in object-oriented programming. Notably, a default constructor invariably exists within any given program employing objects - created seamlessly by the compiler for effortless utilization.

In this discourse, we shall delve into constructor overloading with a static block in Java. Constructor overloading is a concept of defining multiple constructors with different parameters in a class.

Syntax

Public class class_name {
   Class_name() {
   }
   Class_name(par1, par2..) {
   }
}

Using a constructor with a static block provides more functionality and flexibility during object initialization.

Algorithm

Constructor overloading with static block, follow the steps below −

  • Step 1 − Create a class with multiple constructors having different parameters.

  • Step 2 − Create a static block with the ‘static’ keyword

    This block will execute once when the class is loaded into memory.

  • Step 3 − When a class is loaded, static blocks are executed first, then constructors when an object is created.

  • Step 4 − the constructor will be called according to the arguments provided.

Approach 1: Define separate static block

This approach involves defining static blocks and overloaded constructors separately.

Example

Class Class_name{
   Static {
   }
   Public class_name(){
   }
   Public class_name(int value) {
   }
   Public class_name(string name) {
   }
   //Other methods
}

In this approach, the class can have overloaded constructors with different argument lists that also include the initialization code. And a separate static block for static initialization of the class. This block will be executed once.

Example 

In this example, we will demonstrate Approach 1

class Emp { int id, exp;String name;static String company;
   static { company = "XYZ Corp"; }
   public Emp(){
      System.out.println("-"
                           + "\t"
                           + "-"
                           + "\t"
                           + "-"
                           + "\t"
                           + "\t"
                           + "-"); }
   public Emp(int id, String name){ System.out.println(id + "\t" + name + "\t"
                           + company + "\t" + exp); }
   public Emp(int id, String name, int exp) {
      System.out.println(id + "\t" + name + "\t"  + company + "\t" + exp); }
}
public class Way2Class {
   public static void main(String[] args) {
      System.out.println("Id"
                           + "\t"
                           + "Name"
                           + "\t"
                           + "Company"
                           + "\t"
                           + "Exp");
      Emp obj1 = new Emp(001, "Apoorva");
      Emp obj2 = new Emp(004, "Anu", 10);
      Emp obj3 = new Emp();
   }
}

Output

Id	Name	Company	Exp
1	Apoorva	XYZ Corp	0
4	Anu	XYZ Corp	10
-	-	-		-

Explanation

In a company employees with any number of years of experience will be in the same company. Therefore if no value is passed in the company variable then it automatically set the company name with the same company. For this, we used static block.

Approach 2: Invoke Static Methods from Constructors

To execute the shared initialization code, you can declare static methods in your class and call them from the constructors.

Example

public class Way2Class {
   private int value;
   private String name;

   private static void initialize() {
      System.out.println("Common initialization code");
   }

   public Way2Class() {
      initialize();
      value = 0;
      name = "Default";
      System.out.println("No-arg constructor called");
   }

   public Way2Class(int value) {
      initialize();
      this.value = value;
      name = "Value";
      System.out.println("Int constructor called");
   }

   public Way2Class(String name) {
      initialize();
      value = 0;
      this.name = name;
      System.out.println("String constructor called");
   }

   public static void main(String[] args) {
      Way2Class obj1 = new Way2Class();
      Way2Class obj2 = new Way2Class(10);
      Way2Class obj3 = new Way2Class("Hello");
   }
}

Output

Common initialization code
No-arg constructor called
Common initialization code
Int constructor called
Common initialization code
String constructor called

Explanation

The class Way2Class in this illustration includes three constructors, each of which invokes the static initialize () method to execute shared initialization code. Each constructor calls the static function initialize (), which is specified within the class. Based on the arguments given, the appropriate constructor is called during object creation, and the static method initialize () is used to execute the common initialization code.

Comparison of Approach 1 and Approach 2

Criteria

Approach 1

Approach 2

Type

separate static block

Invoke Static Methods from Constructors

Method

Reusing common static methods with the different constructors.

The separate static method with the common constructor.

Method Logic

Constructor overloading with static block

Constructor overloading with static block

Conclusion

While Approach 2 (Static Methods Invoked from Constructors) offers greater flexibility in terms of code organization and inheritance, Approach 1 (Multiple Constructors with Common Code) is more self-contained and simple. The choice between the two approaches depends on the specific requirements and design considerations of the project at hand.

Updated on: 01-Aug-2023

259 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements