Constructor in java

Constructor
Constructor is like as a method that used to initialize the object

Rule:

  • Constructor name must be same as its class
  • Constructor must have no explicit return type
  • Constructors are called automatically as soon as object gets created

Type of constructor:
1.Default constructor

  • Default constructor refers to a constructor that is automatically created by compiler in the absence of explicit constructors.
  • we also call a constructor without parameters as default constructor
Syntax:Default constructor
class ClassName
{
ClassName()
{
// Statement;
}
}

2.Parameterized constructor

  • it can take argument
  • argument can be of any type
  • it can take any number of argument
Syntax:Parameterized constructor
class ClassName
{
ClassName(arguments)
{
// Statement;
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *