Constructor in Java: In Java, a constructor is a special method used to create and initialize class objects. Constructors are called automatically when an object of the class is created, and their main purpose is to set the initial values of the object’s instance variables.
Before starting our discussion about Constructor, Let us inform you that we have a dedicated post where we have shared all the topics of Java, and you can find that post by clicking on the Core Java Tutorial link.
In this article, we will explore constructors in Java in detail, including how to create them, their purpose, and how to overload them.
What is Constructor in Java?
In Java, a constructor is a block of code similar to a method but not an actual one because it initializes the newly created objects. When an object of a class is created using the new keyword, the constructor of that class is automatically called constructor to initialize the object. The primary purpose of a constructor is to set the initial values of the object’s instance variables, which are the variables that belong to the object and hold its state.
In Java, constructors have the same name as the class and can be overloaded, meaning a class can have multiple constructors with different parameter lists. When you define a constructor with parameters, you can pass values to it when you create an object. The constructor will use those values to initialize the object’s instance variables.
How to Define a Constructor in Java
There are some predefined rules which we need to follow at the time of creating a constructor, that is:
- The constructor name should be the same as the class name.
- The constructor must have no explicit return type
- A Java Constructor cannot be abstract, static, final, or synchronized.
A constructor is declared like any other method but has no return type, not even void. The syntax for a constructor is as follows:
public ClassName() { // constructor body }
If you are creating any methods with the same name as the class that does not have any parameter, then we call that default constructor, which takes no arguments. It is automatically created by the Java compiler if no constructor is explicitly defined in the class. However, the default constructor is not created if you define a constructor with parameters.
public ClassName(int parameter1, String parameter2) { // constructor body }
In this case, the constructor takes two parameters: an int and a String. You can define as many parameters as needed to initialize the class’s instance variables.
Let’s take a simple Java program example and try to understand how a Java constructor is declared. In the below, you can see there is a simple MyClass java class with a single constructor.
public class MyClass { public MyClass() { // constructor body } }
In the above example:
public MyClass() { // constructor body }
In the above case, MyClass() Is a constructor; from that, Public is an access modifier. It has the same meaning as for the methods and variables. By this, we determine what classes can access the constructor.
The second part is the constructor’s name, MyClass, which is also the same as the class name. Using the class name for the constructor signals to the Java compiler that it is a constructor. You can find no return type like our methods if you have noticed.
The third part of the Java constructor is the list of parameters a constructor can take. We can define the parameter inside the (). In the above declaration, you can see that we have not mentioned any parameters. Later, we will see examples of how to define parameters for a constructor.
The Fourth part is the body part of a constructor, which we can define inside the brackets {}. In the above example, we have not defined the body for the constructor; that’s why such a type of constructor is called an “empty” constructor.
Purpose of Constructor in Java
The primary purpose of constructors is to initialize the class’s instance variables. When an object of the class is created, the constructor is called automatically and sets the initial values of the object’s instance variables. Without constructors, objects would be created with default values for their instance variables, which may not be suitable for the program’s needs.
How Does the Constructor Work in Java?
For example, let’s say we have a person class with two instance variables: name and age. We can define a constructor that takes two parameters, one for the name and one for the age, and uses them to initialize the instance variables:
package com.softwaretestingo.Constructor; public class Person { private String name; private int age; public Person(String name, int year) { this.name = name; this.age = year; } public static void main(String[] args) { Person obj=new Person("Ramesh", 2023); } }
Now, when we create an object of the Person class [Person obj=new Person(“Ramesh”, 2023);], we can pass in values for the name and age parameters, and the constructor will set the instance variables to those values.
This creates a new Person object named “Ramesh” and age 25.
Example 2:
Creating an object like that internally invokes the constructor to initialize the newly created object. You may be a little bit confused regarding how it initializes. Let’s take another example to know it a better way:
public class Hello { String name; //Constructor Hello() { name = "www.softwaretestingo.com"; } public static void main(String[] args) { Hello obj = new Hello(); System.out.println(obj.name); } }
In the above example, we are creating an object by using the new keyword, like below
Hello obj=new Hello();
When the Java compiler executes the above statement, it calls the constructor to initialize the variables or members. After completing the execution of the constructor again, the flow returns to the main method for executing the rest of the statements.
Types Of Constructors In Java
In Java, we have mainly three types of constructors:
- Default Constructor
- No-arg Constructor
- Parameterized Constructor
Default Constructor In Java
It is not compulsory to provide a constructor in a class. If you don’t define any constructor for a class, the compiler will create a default constructor for you. This constructor has no parameters and does not perform any initialization. Let’s take a simple Java program to understand where a default constructor is used since we have not mentioned any constructor.
public class Data { public static void main(String[] args) { Data d = new Data(); } }
Important Point Of Default Constructor
- The main role of the default constructor is to initialize the object and return the execution flow to the calling code.
- When no constructor is defined in the class, the Java compiler provides a default constructor, always without any argument.
No Argument Constructor in Java
When a constructor without any argument or parameter is called a No-arg constructor, it’s similar to the default constructor. Let’s have a look at the No-arg constructor in Java.
class Demo { public Demo() { System.out.println("This is a no argument constructor"); } public static void main(String args[]) { Demo obj = new Demo(); } }
When Demo obj = new Demo(); statement executes, It calls the Demo constructor and prints the message in the console.
Parameterized Constructor in Java
A Constructor with an argument/parameter is called a parametrized constructor. If we want to initialize the members or fields of a class with our own, we have to use a parameterized constructor.
public class Employee { int empId; String empName; //parameterized constructor with two parameters Employee(int id, String name){ this.empId = id; this.empName = name; } void info() { System.out.println("Id: "+empId+" Name: "+empName); } public static void main(String args[]) { Employee obj1 = new Employee(10245,"Chaitanya"); Employee obj2 = new Employee(92232,"Negan"); obj1.info(); obj2.info(); } }
What Happens If A Class Provides Only A Parameterized Constructor?
If a class provides only a parameterized constructor, and no default constructor is defined, it becomes mandatory to provide the required arguments while creating an object of that class. A compilation error will occur if you try to create an object of such a class without passing any arguments.
class Example3 { private int var; public Example3(int num) { var=num; } public int getValue() { return var; } public static void main(String args[]) { Example3 myobj = new Example3(); System.out.println("value of var is: "+myobj.getValue()); } }
This class has only one constructor that takes one parameter, which is num. If you try to create an object of this class without passing num arguments, as shown below, a compilation error will occur:
Example3 p = new Example3(); // Compilation error: constructor Person in class Person cannot be applied to given types
To create an object of this class, you must provide the required arguments, as shown below:
Example3 p = new Example3(25);
In general, providing only a parameterized constructor is useful when you want to ensure that objects of the class are always created with specific initial values, and you don’t want to allow objects to be created with default values. This can help improve your code’s design and reliability, ensuring that objects are always created with a valid state.
However, it does require the caller to provide the required arguments when creating objects, which can be a potential drawback if the caller does not have access to all the required information.
Constructor Chaining
Constructor chaining is a technique in Java that allows constructors to call other constructors in the same class. This is done using this keyword, which refers to the currently constructed object. You can reuse code and simplify initializing the object state by calling another constructor in the same class.
Constructor Chaining Using This()
package com.softwaretestingo.Constructor; public class ConstructorChainingEx { private String name; private int age; public ConstructorChainingEx() { System.out.println("Default Constructor"); } public ConstructorChainingEx(String name) { //Invokes Default Constructor this(); System.out.println("One Parameterized Constructor"); } public ConstructorChainingEx(String name, int age) { this(name); System.out.println("Two Parametrized Constructor"); } public static void main(String[] args) { ConstructorChainingEx p1=new ConstructorChainingEx("SoftwareTestingo", 2023); } }
Output:
Default Constructor One Parameterized Constructor Two Parametrized Constructor
Constructor Chaining Using Super()
Whenever a child class constructor wants to call the parent class’s constructor at that time implicitly, we can use the super(); in all the sub-classes, the first statement of a child class constructor is a super(); statement.
package com.softwaretestingo.Constructor; class Base { String name; // constructor 1 Base() { this(""); System.out.println("No-argument constructor of" +" base class"); } // constructor 2 Base(String name) { this.name = name; System.out.println("Calling parameterized constructor"+ " of base"); } } public class ConstructorChainingUsingSuperEx extends Base { // constructor 3 ConstructorChainingUsingSuperEx() { System.out.println("No-argument constructor " +"of derived"); } // parameterized constructor 4 ConstructorChainingUsingSuperEx(String name) { // invokes base class constructor 2 super(name); System.out.println("Calling parameterized " +"constructor of derived"); } public static void main(String[] args) { // calls parameterized constructor 4 ConstructorChainingUsingSuperEx obj = new ConstructorChainingUsingSuperEx("test"); } }
Output:
Calling parameterized constructor of base Calling parameterized constructor of derived
Constructor Overloading
Constructor overloading is a feature in Java that allows a class to have multiple constructors with different parameter lists. By using constructor overloading, you can create objects of a class differently, depending on the parameters passed to the constructor. This provides flexibility in the creation of objects and makes the class more versatile.
To overload constructors, you define multiple constructors with different parameter lists in the class. For example, consider the following class:
package com.softwaretestingo.Constructor; public class Person1Ex { private String name; private int age; public Person1Ex(String name, int age) { this.name = name; this.age = age; } public Person1Ex(String name) { this(name, 0); } public Person1Ex(int age) { this("Unknown", age); } public static void main(String[] args) { Person1Ex p1=new Person1Ex("SoftwareTestingo", 2023); Person1Ex p2=new Person1Ex("SoftwareTestingo"); Person1Ex p3=new Person1Ex(2023); } }
Constructor overloading can be useful for creating more flexible and versatile classes. Providing multiple ways to create objects makes your classes more user-friendly and easier to use.
Copy Constructor
In Java, a copy constructor is a constructor that takes an object of the same class as a parameter and creates a new object with the same state as the original object. The purpose of a copy constructor is to create a new object with the same values as an existing object without modifying the existing object.
package com.softwaretestingo.Constructor; public class CopyConstructorEx { private String personName; private int personAge; //constructor to initialize personName and personAge CopyConstructorEx(String name, int age) { personName=name; personAge=age; } //creating a copy constructor CopyConstructorEx(CopyConstructorEx obj) { System.out.println("Invoking the Copy Constructor:"); personName=obj.personName; personAge=obj.personAge; } //creating a method that returns the price of the fruit String showName() { return personName; } //creating a method that returns the name of the fruit int showAge() { return personAge; } public static void main(String[] args) { CopyConstructorEx conobj=new CopyConstructorEx("Ramesh",23); System.out.println("Name of the Person: "+conobj.showName()); System.out.println("Age Of the Person :"+conobj.showAge()); //passing the parameters to the copy constructor CopyConstructorEx conobj1=new CopyConstructorEx(conobj); System.out.println("Name of the Person: "+conobj.showName()); System.out.println("Age Of the Person :"+conobj.showAge()); } }
Output:
Explanation:
The CopyConstructorEx class has two instance variables, personName and personAge. The class has two constructors: one is a parameterized constructor to initialize the instance variables, and the second one is the copy constructor, which takes an object of the same class as its argument.
In the parameterized constructor, personName and personAge are initialized with the values passed in the constructor arguments.
In the copy constructor, the object’s state is copied from the object passed as an argument to the newly created object. The values of personName and personAge are assigned from the object passed as an argument.
The class also has two methods, showName() and showAge(), which return the personName and personAge values, respectively.
In the main method, an object of the CopyConstructorEx class is created with the name conobj by passing values “Ramesh” and 23 to the constructor. The showName() and showAge() methods are called on conobj to display the values of personName and personAge.
Then, a new object, conobj1, is created by passing conobj as an argument to the copy constructor. The showName() and showAge() methods are called on conobj1 to display the values of personName and personAge, which are the same as those of personName and personAge of conobj.
Private Constructor In Java
A constructor can be made private by using the private access modifier. The private constructor can only be accessed within the class it declares, and you cannot be accessed outside the class, not even by its child class or any other class in the same package.
The primary reason for making a constructor private is to prevent the creation of objects of the class from outside the class. This is useful in certain scenarios, such as when the class is designed to have only static methods and cannot be instantiated or when a singleton design pattern is used.
In a singleton design pattern, a class is designed to have only one instance throughout the lifetime of an application. To achieve this, the class’s constructor is made private, and a static method is provided to access the class instance. This ensures that only one class instance is created and used throughout the application.
Here’s an example of a class with a private constructor:
Output:
package com.softwaretestingo.Constructor; class MySingleton { static MySingleton object = null; public int number = 10; // private constructor private MySingleton() { } // Factory method to provide the users with object static public MySingleton displayInstance() { if (object == null) object = new MySingleton(); return object; } } public class PrivateConstructorEx { public static void main(String[] args) { MySingleton obj1=MySingleton.displayInstance(); MySingleton obj2=MySingleton.displayInstance(); //Increase the Value of number Variable using one object obj1.number = obj1.number+30; System.out.println("The Value of Number Variable of Object 1 :"+obj1.number); System.out.println("The Value of Number Variable of Object 2 :"+obj2.number); } }
The Value of Number Variable of Object 1 :40 The Value of Number Variable of Object 2 :40
Explanation:
In this example, the MySingleton class has a private constructor, which prevents the creation of objects of this class from outside the class. The class also has a static method displayInstance(), which is used to access the singleton instance of the class. The displayInstance() method checks if an instance of the class has already been created, and if not, it creates a new instance and returns it.
To use the MySingleton class, we can call the displayInstance() method as follows:
MySingleton obj1=MySingleton.displayInstance();
The first time this method is called, it creates a new instance of the MySingleton class, and all subsequent calls return the same instance. Since the class’s constructor is private, no other class instances can be created outside the class.
Class1 has a Private constructor and non-static method and you need to call the class1 method from another class <>
Solution:
If class1 has a private constructor and a non-static method, it means that instances of class1 cannot be directly created outside of the class, and the non-static method can only be accessed through an instance of class1. However, if your requirement is to access the method of class1 from class2, you can achieve this by creating a public method in class1 that returns an instance of class1, and then call the non-static method on that instance from class2. This is commonly known as a factory method pattern.
public class class1 { // Private constructor private class1() { // Constructor logic here } // Non-static method public void method1() { // Method logic here System.out.println("Method1 called from class1"); } // Public static factory method to get an instance of class1 public static class1 getInstance() { return new class1(); } } public class class2 { public static void main(String[] args) { // Accessing method1 from class2 class1 obj = class1.getInstance(); obj.method1(); } }
In this example, class2 creates an instance of class1 using the public static factory method getInstance(), and then calls the non-static method method1() on that instance. This allows class2 to access the method of class1 even though the constructor of class1 is private and the method in class1 is non-static.
How did Default Constructor & Static Block call In Java With Example?
package com.softwaretestingo.Constructor; public class DefaultconstructorCallingVSStatic { DefaultconstructorCallingVSStatic () { System.out.println ("Default Constructor Called"); } static { System.out.println ("Static Block Executed"); } public static void main (String[]args) { DefaultconstructorCallingVSStatic obj = new DefaultconstructorCallingVSStatic (); } }
Output:
Static Block Executed Default Constructor Called
How do you check whether a child class inherits constructors of another class or not?
package com.softwaretestingo.Constructor; class a { a() { System.out.println("Super Class Constructor Called"); } } public class Class_inherits_Class_ConstructorEx extends a { //Child Class Constructor called parent class constructor public Class_inherits_Class_ConstructorEx() { } public static void main(String[] args) { Class_inherits_Class_ConstructorEx obj=new Class_inherits_Class_ConstructorEx(); } }
Output:
Super Class Constructor Called
Ref: article
This is the Best Site for the Software Test Engineers