Last Updated on August 25, 2023 by Mayank Dham
In the world of Java programming, constructors play a fundamental role in object-oriented design, acting as the foundation upon which instances of classes are created. Constructors are like the architects of objects, responsible for initializing their state and preparing them for operation. Understanding the concept and significance of constructors is essential for any Java developer aiming to build efficient, organized, and maintainable code. In this article, we will unravel the intricacies of constructors in Java. We will delve into their types, usage scenarios, and best practices, providing a clear understanding of how they contribute to the seamless functioning of Java applications. Let’s discuss “what is constructor in java” now.
What is a Constructor in Java?
A constructor is a special method that is automatically called when an instance of the class is created. Constructor in java always has the same name as the class name (including the first character capital). New object memory is allocated while calling the constructor. A constructor can be used to set the initial code to be executed while creating a new object of the class.
Constructor Example:-
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:-
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.
Rules to define a constructor in java:
- A constructor must have the same name as the class name
- A constructor must not have any return type
- A constructor can not be static, final, abstract, and synchronized.
Let’s see how we can set the initial code using the constructor in java with the help of an example.
Types of constructor program in java:-
Firstly, there are two types of constructor in java.
- No-Argument Constructor program in java
- Default Constructor program in java
- Parameterized Constructor program in java
No-Argument Constructor program in java:-
A no-argument constructor is similar to java methods but the main differences are that a no-argument constructor does not have any return type and it does not accept any parameters. Let’s see how to write a no-argument constructor program in java.
public class PrepBytes { public PrepBytes() { System.out.println("No-Argument constructor is called!”); } public static void main(String[] args) { PrepBytes pb= new PrepBytes(); } }
Output:-
No-Argument constructor is called!
In the above program, we have created a no-argument constructor and it is called automatically when we create an object of the class PrepBytes.
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. If we create any of the constructors then the java compiler does not create the default constructor. Let’s understand how to write a default constructor program in java.
Example:-
public class PrepBytes { int num; public static void main(String[] args) { // here default constructor prepbytes() is called PrepBytes pb=new PrepBytes(); System.out.println("Default Value of num= "+pb.num); } }
Output:-
Default Value of num= 0
In the above example, we have not created any constructor but the java compiler automatically creates a default constructor.
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.
Constructor overload program in java:-
We can overload a constructor in java giving different arguments to each constructor. We can also give different types of arguments like int, float, double, etc. Let’s see how to write an overload constructor program in java.
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 constructors with different arguments and while we create an object of class it calls a particular constructor based on given arguments. In the output, we can see that each object prints a statement based on given arguments.
Constructor Override in java:-
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. Let’s see the override constructor program in java.
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
Conclusion
In conclusion, understanding constructors in Java is essential for any aspiring Java developer. Constructors are special methods used to initialize objects and set their initial states. They play a crucial role in object-oriented programming by allowing us to create instances of classes with specific initial values. By grasping the concepts of default constructors, parameterized constructors, and constructor chaining, developers can create more efficient, organized, and flexible code.
Constructors facilitate the process of creating objects and provide a seamless way to pass initial values to object attributes. They allow us to encapsulate initialization logic within the class, ensuring that objects are set up correctly from the moment they are created. Constructors not only enhance the readability and maintainability of code but also enable the implementation of more complex software systems.
FAQs Related to Constructor
1. 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. |
2. 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.
Q3: Are constructors required in a Java class?
A3: No, constructors are not required in a Java class. If a class does not explicitly define any constructors, a default constructor (with no parameters) is automatically provided by the Java compiler. However, if you define any constructors in the class, the default constructor won’t be automatically generated.
Q4: What is constructor overloading?
A4: Constructor overloading is a technique in Java where a class can have multiple constructors with different parameter lists. This allows you to create objects with different initializations based on the parameters provided when constructing the object.
Q5: How can I call one constructor from another in Java?
A5: Constructor chaining is the process of calling one constructor from another constructor within the same class. This is achieved using the this() keyword, followed by the appropriate constructor parameters. This helps avoid code duplication and ensures that all necessary initialization steps are performed.