Constructor in Java

Edu Tech Learner
0


A constructor in Java is a special method that is used to initialize an object of a class. It can be used to set initial values for the object attributes, such as length, width, height, name, etc. A constructor has the same name as the class name and does not have any return type. There are two types of constructors in Java: default constructor and parameterized constructor.

  • A default constructor is a constructor that does not take any parameters. It is automatically created by the Java compiler if no constructor is defined in the class. It provides the default values to the object attributes, such as 0, null, etc., depending on the type. For example, the following class has a default constructor:
class Box {                                     
  int length;                                   
  int width;                                    
  int height;                                   
                                                
  // default constructor                        
  Box() {                                       
    // assign default values to the attributes  
    length = 0;                                 
    width = 0;                                  
    height = 0;                                 
  }                                             
}                                               
  • A parameterized constructor is a constructor that takes one or more parameters. It is defined by the programmer to initialize the object attributes with specific values. For example, the following class has a parameterized constructor:
class Box {                                      
  int length;                                    
  int width;                                     
  int height;                                    
                                                 
  // parameterized constructor                   
  Box(int l, int w, int h) {                     
    // assign parameter values to the attributes 
    length = l;                                  
    width = w;                                   
    height = h;                                  
  }                                              
}                                                

To create an object of a class using a constructor, we use the new keyword followed by the class name and the constructor arguments (if any). For example:

// create an object using the default constructor      
Box b1 = new Box();                                    
                                                       
// create an object using the parameterized constructor
Box b2 = new Box(10, 20, 30);                          

A constructor is called only once when an object is created. It is used to perform some tasks before the object is available for use, such as memory allocation, initialization, validation, etc.








Post a Comment

0Comments
Post a Comment (0)