Updated March 18, 2023
Introduction to Static Constructor in Java
A static constructor is the piece of code used to initialize static data, which means that a particular task needs to be executed only once throughout the program. It is usually called automatically before any static members referenced or a first instance is generated. A static constructor is the one that is explicitly declared using the “static” keyword. A constructor is not allowed to be static, abstract, final, native, synchronized or strictfp in Java.
They have a few unique features as follows:
- A static constructor does not take parameters or access modifiers.
- A specific class can possess only a single static constructor.
- Inheritance or overloading is not allowed in static constructors.
- It cannot be called directly since it is always invoked automatically.
- If the static fields initialization values are not provided, then it initializes to their default value as in the Default values table.
Syntax:
public class <Class_Name> {
private <datatype> <variable>;
public static <Constructor_Name> () {}
}
Here we are trying to declare a constructor in the class by defining it as static. When such a code is compiled, we get an error message stating that an Illegal modifier is being used for the constructor in type <Class_Name> and only public, protected and private are allowed.
Working of Static Constructor in Java
Constructors are not allowed to be static in Java because of the following reason:
In Java, static methods and variables apply to the classes. But a constructor is called when a new operator is used to create an instance. Since it does not belong to the property class, it is not allowed to be static. If a constructor is considered static, it cannot be accessed by an object of its subclass.
But if a constructor is allowed to be static, then it can be accessed within the class but not by its subclass. It also cannot be inherited, which means they belong to the class they are declared. Allowing a static constructor breaches the entire concept of inheritance; hence it is illegal.
Examples of Static Constructor in Java
We can understand the concept of Static Constructor in Java better in the following examples:
Example #1
Code:
public class Employee {
//Initialising variables for employee name and ID
public String emp_name;
public int emp_id;
//Declaration of the static constructor
public static Employee(){
System.out.println("Printing Constructor of the Employee class");
}
//Declaring method to print message
public void displayMsg(){
System.out.println("Employee Name is: "+this.emp_name );
System.out.println("Employee ID is: "+this.emp_id );
}
public static void main(String args[]) {
//Creating a new object to call the display message constructor
new Employee().displayMsg();
}
}
Output:
Here we are getting a compilation time error telling us that the modifier static is not allowed for Employee() constructor inside Employee() class since we are calling the same by creating a new object below. This can be solved by not declaring it as static. Check out the example below for the same.
Example #2
We have to create 2 classes inside the same package; ParentExample.java and ChildExample.java, which extends from its parent class.
Code:
ParentExample.java:
public class ParentExample {
ParentExample(){
super();
System.out.println("Printing Super constructor inside Parent class");
}
void displayMessage(){
System.out.println("Printing inside display Message class");
}
}
ChildExample.java:
public class ChildExample extends ParentExample {
ChildExample(){
super();
System.out.println("Printing super constructor inside child class");
}
@Override
void displayMessage(){
System.out.println("Printing display message inside Parent example");
}
public static void main(String[] args){
ChildExample childexample = new ChildExample();
childexample.displayMessage();
}
}
Now run the ChildExample.java.
Output:
Observations:
- Both Parent and Child class have got default constructors with no arguments and a message printed to make the execution flow clear.
- A static constructor is the first block of code to run in the class as they are executed immediately when the respective class execution starts.
- The subclass overrides the display message() method and prints the message.
- We have created a new object of the ChildExample class, which executes the first superclass constructor and then the second subclass.
- At last, the display method of the newly created object is invoked to display the message.
- In such cases where inheritance is implemented, the constructors are called either explicitly or implicitly. Hence it should be made non-static so that it is accessible.
- When it is made a static one, it gets associated with a specific class rather than its instances and will not be available during object instantiation.
Example #3
This example shall combine both of the above static and non-static constructors and check their implementation.
Code:
class ParentClass{
private static String message= "Test message";
// Declaring a nested static class
public static class StaticNestedClass{
// In the nested class only static members belonging to parent class can be accessed
// in a static nested class
public void displayprint() {
// We get a compiler error if we try and make this message
// a non-static variable
System.out.println("Displaying from nested class: " + message);
}
}
// Declaring Inner class or also called non-static nested class
public class ChildClass{
// The static and non-static constructor both can be accessed in
// this Child class
public void displayprint(){
System.out.println("Printing from static non-nested class: "+ message);
}
}
}
class Main
{
public static void main(String args[]){
// Instance of static nested class creation
ParentClass.StaticNestedClass printer = new ParentClass.StaticNestedClass();
//Calling the non-static constructor of static nested class
printer.displayprint();
// Creating Parent class instance first in order
//to create the child class instance
ParentClass outer = new ParentClass();
ParentClass.ChildClass inner = outer.new ChildClass();
// Here we call the non-static method of Child class
inner.displayprint();
// Creation of instance for child class in one line
//by combining above 2 lines
ParentClass.ChildClass innerObject = new ParentClass().new ChildClass();
// Now we call the child method
innerObject.displayprint();
}
}
Output:
Limitations of Static Constructor in Java
Here are some limitations of static constructor in java given below:
- Constructor names cannot be explicit ones, and they must be mandatorily the same as their class name. Since they are confined to these conventions, more readable names cannot be given to them.
- Every time a constructor needs to be called, a new object has to be created. This also affects the performance of the code, thus making it slow.
- Return types of constructors are restricted to return the same type as that of the object.
- We cannot use static constructors in subclass construction as the implementation of only superclass constructors is allowed.
- A static constructor does not allow the use of “this” keyword to access an instance.
- Testing efforts required are more where static constructors are involved.
Conclusion
The main job of a constructor is for initializing an object, and as seen from all the above examples, a constructor is not allowed to be static for the main reason that the object of a subclass and other non-static members cannot be accessed by it. The alternative to the static constructor is using static blocks of code to initialize a class’s static variables.
Recommended Articles
This is a guide to Static Constructor in Java. Here we discuss the basic concept, working, limitations, and examples of static constructors in java in java along with their implementation. You may also look at the following articles to learn more–