Example of a Constructor in Java

In this post we are going to create a class in Java with constructor. So let's see how to create a class in Java which contains constructor method.  

First of all we need to know what is a constructor in Java.


What is a Constructor in Java:

In a simple words constructor in Java is a special type of method which is used to initialize an objects. Constructor has the same name as that of the class name and it does not return any value.
It is called automatically when an instance of the class is created. 



Thers are three types of constructor in Java :

  1. No-Arg Constructor
  2. Parameterized Constructor
  3. Default Constructor


1. No-Arg Constructor: 

When constructor doesn't have any parameters then it is called as no-arg constructor.

Example of No-Arg Constructor:


//Example of no-arg constructor
class Car{
	
    //Constructor with no parameter
    Car(){
    	System.out.println("No-arg constructor is called....");
    }
    
    public static void main(String[] args){
    	
        //calling a no-argument constructor
        Car obj = new Car();
    }
}

OUTPUT:
No-arg constructor is called....


2. Parameterized Constructor:

A constructor which accepts one or more parameters is called as a parameterized constructor.


Example of Parameterized Constructor:


//Example of parameterized constructor
class Car{
    String cName;
    
    //Parameterized Constructor
    Car(String name){
    	cName = name;
        System.out.println("Name of the car is: "+cName);
    }
    
    public static void main(String[] args){
        //Calling constructor by passing value(parameter)
    	Car obj1 = new Car("Porsche Taycan");
        Car obj2 = new Car("Lamborghini Aventador");
    }
}


OUTPUT:
Name of the car is : Porsche Taycan
Name of the car is : Lamborghini Aventador



3. Default Constructor:

A default constructor is a constructor which is automatically created by java compiler to provide default values to the object like null, 0 etc. depending on the type.

Example of the default Constructor:


//Example of default constructor
class Car{
    String cName;
    int speed;
        
    public static void main(String[] args){
        //A dafault constructor is called
    	Car obj = new Car();
        
        //Default constructor will assign the following default values
        System.out.println("Default value for car name is : "+obj.cName);
        System.out.println("Default value for car speed is : "+obj.speed);
    }
}


OUTPUT:
Default value for car name is : null
Default value for car speed is : 0 



That's all about constructor and types of the constructor in java. If you have any doubts then feel free to comment below in the comment section. If you think this article is helpful then please share it with your  friends and colleagues.

No comments:

Post a Comment

If you have any doubts, please discuss here...👇