DEV Community

Ajay Sundar
Ajay Sundar

Posted on

Constructor in java

A constructor is a special block of code that is called when an object is created. Its main job is to initialize the object, to set up its internal state, or to assign default values to its attributes.

Characteristics of constructors

  1. Same Name as the Class: A constructor has the same name as the class in which it is defined.

  2. No Return Type: Constructors do not have any return type, not even void. The main purpose of a constructor is to initialize the object, not to return a value.

  3. Automatically Called on Object Creation: When an object of a class is created, the constructor is called automatically to initialize the object’s attributes.

  4. Used to Set Initial Values for Object Attributes: Constructors are primarily used to set the initial state or values of an object’s attributes when it is created.

An example of constructor

class Market {
    String groceries;
    String color;
    double weight;
    int rate;

   Market (String groceries,String color,double w,int rate) {
       //this. is current object
       this.groceries = groceries;
       this.color = color;
       this.weight = w;
       this.rate = rate;
   }
       void groceries(){
           System.out.println("groceries:"+groceries);
       }
       void color(){
           System.out.println("Color:" +color);
       }
       void weight(){
           System.out.println("weight:"+weight);
       }
       void amount(){
           System.out.println("rate:"+rate);
       }

    public static void main(String[] args){
       Market obj= new Market("Sugar","White",54,78);


       obj.groceries();
       obj.color();
       obj.weight();
       obj.amount();

    }
}



Enter fullscreen mode Exit fullscreen mode
OUTPUT

groceries:Sugar
Color:White
weight:54.0
rate:78

Enter fullscreen mode Exit fullscreen mode

Top comments (0)