Constructors in java


Constructors are used to initialize some of the parameters in any program in java constructor is used for initializing some functionality as well as to create an object instance. let us see how.

The constructor is a way to create instance of the Java class. The can be identified in the code easily, as it has the same name as the class for which it is defined. The syntax of the constructor is as follows,


Scope-Identifier[optional/public] ClassName(arguments[optional]){
//constructor body
}

The constructor usually contains the code for the initialisation as this is the first element of the class which gets called by the execution environment. The body of constructor is usually same like for method body, or better say you can do whatever you want with the constructor too. if you don't specify the constructor for a class, the execution environment itself provides the default constructor, for example in the class below,*/


class Car{
}

//you can also write it as

class Car{
    //constructor
    Car(){
    }
}

and this makes no difference for the system as long as you don't have anything to put in as arguments or in body. We can have more than one constructor for a class but that other constructor will have a different signature. for example we can make car as


class Car{
    int speed;
    boolean transmissionMode;
    //default or parameter less constructor
    Car(){
}
    
//parametrised constructor
Car(int s, boolean tm){
        this.speed = s;
       this.transmissionMode = tm;
  }
}

If you see there are two constructors defined but with different signature. This concept is known as constructor overloading and is a part of polymorphism concept. In the second constructor we have given arguments, which can be used to initialise the car class with a start up speed and transmission mode. you can use the constructor to instantiate a class and create an object like this.

Car bmw = new Car(); // using default constructor
or
Car bmw = new Car(10,true); //using parameterized constructor

to initialise at a speed of 10 and transmission mode true, by passing parameters.