Last Updated on May 16, 2023 by Prepbytes
Constructor is invoked when an object of the class is generated and is quite similar to a method. In most cases, a constructor is used to execute the initial blocks of code when constructing a class object. With the aid of examples, we will learn about constructors in Java, their different kinds, and how to utilise them in this article.
What is a Constructor in Java?
When a class instance is created, a specific function called the constructor is launched. In Java, the constructor is always given the same name as the class, up to and including the initial capital letter. When the constructor is called, new object memory is allocated. To provide the first code to run when creating a new object of the class, use the constructor.
Let’s see how we can set the initial code using the constructor in java with the help of an example.
Example of Constructor:
class PrepBytes{ // Constructor with the same name as the class name PrepBytes(){ System.out.println("Constructor is called"); } public static void main(String[] args) { // Create a new object of the class PrepBytes pb=new PrepBytes(); } }
Output:
constructor is called
In the above example, we created a method with no return type and the same name as the class name ( PrepBytes() ), this method is called a constructor. Now we created an object of the class PrepBytes using the new() keyword, constructor is automatically called and assigned memory when we create an object of the class. In the output, we can see that ‘Constructor is called’ is printed without we called constructor so the constructor is automatically called we if we don’t call it.
Let’s see another example of how we can assign an initial value to the variable using a constructor in java.
Another Example of Constructor
class PrepBytes { int num1,num2; // Constructor with the same name as the class name PrepBytes(int num){ this.num1=num; // assign value num to num1 } public static void main(String[] args) { // Create a new object of the class PrepBytes pb=new PrepBytes(10); System.out.println(pb.num1); System.out.println(pb.num2); } }
Output:
Value of num1: 10
Value of num2: 0
In the above example, we have declared two variables of type int, and in the constructor, we assign the value of num to the variable num1. In the output, we can see that value of num1 becomes 10 and the value of num2 is still 0 which is the default value of any variable with data type int. This is how we can use a constructor in java to set initial values to the variable.
Types of Constructor in Java
Firstly, there are two types of constructor in java.
- Default Constructor
- Parameterized Constructor
-
Default Constructor with an example:-
A default constructor is a constructor with no arguments given in parentheses. If we don’t create any default constructor or parameterized constructor then the java compiler automatically creates the default constructor and if we create any of the constructors then the java compiler does not create the default constructor. Let’s understand how we can create this type of constructor in java with help of an example.Example:-
public class PrepBytes { PrepBytes(){ System.out.println("Default Constructor is created!"); } public static void main(String[] args) { PrepBytes pb=new PrepBytes(); } }
Output:
Default Constructor is created!
In the above example, we created a default constructor PrepBytes(), and now while creating an object of the class PrepBytes the default constructor is automatically called.
-
Parameterized Constructor with an example:-
A parameterized constructor is a constructor with arguments given in parentheses. We can declare a parameterized constructor in the same way we declare a method with arguments but no return type. Parameterized constructor is generally used to assign initial values to the variables of the class. Let’s understand how we can create this type of constructor in java with help of an example.Example:-
public class Add { int num1,num2,sum; // Parameterized constructor Add(int num1,int num2){ this.num1=num1; this.num2=num2; this.sum=this.num1+this.num2; System.out.println("Sum of "+this.num1+" and "+this.num2+" is: "+this.sum); } public static void main(String[] args) { Add add=new Add(5,10); } }
Output:
Sum of 5 and 10 is: 15
In the above example, we created a parameterized constructor Add with two arguments num1 and num2 data type int. Now we create an object of the class Add in the main method and we give arguments (values of the num1 and num2) while creating an object of the class in the default constructor we didn’t give any arguments while creating an object of class. In the constructor Add we assign values of num1 and num2 variables with given arguments ( Add(5,10) ) and we assign the addition of both variables to the sum variable. In the output, we can see that values of num1 and num2 are initialized using the parameterized constructor. This type of constructor in java is very useful when we want to set some initial code block.
Use of Constructor in Java
These are some important use of constructor in java:-
- Constructors can be used to set initial values for object attributes.
- We can set the initial block of the statement to be executed while creating an instance of the class using a constructor in java.
- Constructor is used to allocate approximate memory to the object and it is used to initialize the object
Conclusion
In conclusion, constructors are an essential part of object-oriented programming in Java. They are used to initialize the state of objects when they are created and allow for the creation of objects with specific values for their instance variables.
Constructors can be overloaded to allow for the creation of objects with different initial values, and they can also be used to enforce constraints on object creation and prevent objects from being created in an invalid state.
It’s important to keep in mind that constructors are not methods and have some distinct differences, such as not having a return type and having the same name as the class. Understanding how constructors work and how to use them effectively is an important skill for any Java programmer.
FAQs related to Constructor in Java
- What is the difference between a method and a constructor?
Method in Java | Constructor in Java |
---|---|
Method is a block of code that is executed only when a method is called. | Constructor is always called when an instance of an object is created. |
Method name can be or can not be the same as the class name | Constructor name must be as the class name |
Method must have a return type. | A constructor must not have a return type. |
Java compiler does not create any default method. | Java compiler does create a default constructor. |
-
Can we overload a constructor in java?
Yes, we can overload a constructor in java giving different arguments to each constructor. Let’s see how we can overload the constructor in java with help of an example.Example:-
public class Add { Add(int num1,int num2){ int sum=num1+num2; System.out.println("Sum of "+num1+" and "+num2+" is: "+sum); } Add(double num1,double num2){ double sum=num1+num2; System.out.println("Sum of "+num1+" and "+num2+" is: "+sum); } Add(int num1,int num2,int num3){ int sum=num1+num2+num3; System.out.println("Sum of "+num1+","+num2+" and "+num3+" is: "+sum); } public static void main(String[] args) { Add add1=new Add(5,10); Add add2=new Add(4.3,7.5); Add add3=new Add(3,4,5); } } Output:- Sum of 5 and 10 is: 15 Sum of 4.3 and 7.5 is: 11.8 Sum of 3,4 and 5 is: 12
In the above example, we created different constructor with different arguments and while we create object of class it calls particular constructor based on given arguments. In the output, we can see that each object prints a statement based on given arguments.
-
Can we override a constructor in java?
No, we can not override the constructor in java. If we try to override the superclass constructor in the subclass then the subclass will treat the superclass constructor as a method because it does not have the same name as the subclass name and throw a compile time error return type is required.Example:-
public class Super{ Super(){ System.out.println("Superclass constructor"); } } public class Sub extends Super { Super(){ System.out.println("Trying to override superclass constructor"); } } Output:- Main.java:16: error: invalid method declaration; return type required Super(){ ^ 1 error
-
Can we use the return type in a constructor?
No, we can not use any return type with the constructor because the constructor always returns an instance of the current class.
For better understanding you can refer below links:
1. Types of Constructor in C++
2. Final Keyword in Java
3. OOPs Concept in Java