Constructor Overloading with Static Block in Java
In Java, Constructor is a block of codes similar to the method that is used to initialize the object’s state. A constructor is invoked at the time of object or instance creation. Each time an object is created using a new() keyword at least one constructor (it could be default constructor) is invoked to assign initial values to the data members of the same class.
Like Method Overloading, we can also overload constructor. In Constructor overloading, we can create multiple constructors with different parameters, Sometimes there is a need of initializing an object in different ways. This can be done using constructor overloading.
In this example, we have created two constructors with the same class name, parameters for each constructor are different, and to access the constructor we pass arguments through the object class. As we are passing the value 10 through object class, the second constructor with int argument gets called, if no value is passed through the object class then the default constructor gets called.
Constructor Overloading with static block
A static block in Java is used for static initializations of a class. Static block executes when the class is loaded in the memory. The code inside the static block is executed only once. Static block can also help in reducing lines of code. Let’s understand why we need Constructor Overloading with a static block in Java. Suppose a company hired a few employees with no experience or two years of experience for a unique role developer. Since newly hired candidates are under the developer category, we can use a static block to do this.
Id Name Category Exp 1863 Kumar Developer 0 1864 ravi Developer 2 - - - -
In the above example, inside the parameterized constructor with two arguments we are passing the only id, name from the object, In the output, we can also see category and exp is also printed, this is because we have created a static block for the category Developer and java automatically assigns 0 if no value is passed to it. Inside the parameterized constructor with three arguments, we are only passing id, name, exp but the category is also printed in output this is because the category is in static block.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.