DEV Community

Kiruthiga S
Kiruthiga S

Posted on

Java

Constructor
- Constructor will called automatically when object is created
- Initializing object specific values
- Constructor name will be same as the class name
- Constructors can have parameters and can be overloaded

Default Constructor
A default constructor has no parameters. It’s used to assign default values to an object.

Argument Constructor
A constructor with arguments (parameters) is called parameterized constructor.
It is used to give values to an object when the object is created.

Zero Argument Constructor
Non-zero argument constructor means a constructor that receives one or more arguments.

Constructor Overloading
Allows a class to have multiple constructors with different parameter lists
provides different ways to initialize objects based on the values available at the time of object creation

public class SuperMarket {
   String prod_name;
   int price;

   public SuperMarket(String str,int i)
   {
      this.prod_name=str;
      this.price=i;
      System.out.println("Constructor called");
   }
   public SuperMarket()
   {
      System.out.println("Zero Constructor called"); 
    }

    public static void main(String[] args)
    {
        SuperMarket product1=new SuperMarket("boost",250);
        SuperMarket product2=new SuperMarket("Horlicks",300);
        SuperMarket product3=new SuperMarket();
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:
Constructor called
Constructor called
Zero Constructor called

Top comments (0)