Constructor in Java and Types

Constructor is very similar to a method and it is called when an object of the class is created. Generally, a constructor is used to perform initial blocks of code while creating an object of the class. In this article, we will learn about what is constructor in java with help of examples, types of constructors in java, and the use of a constructor in java.

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. 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
  1. 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.

  2. 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

FAQs Related to Constructor in Java:

  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.
  1. 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.

  2. 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
    
  3. 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.

Leave a Reply

Your email address will not be published. Required fields are marked *