Search your topic here

Constructor in JAVA

CONSTRUCTORS:

A constructor is a method which called when an instance of an object is created.

If programmer do not provide a constructor for a class, Java will automatically create a default constructor with no parameters and doesn’t initialise any fields.

Default constructor is called if we specify the new keyword without passing parameters.

For example:

Professor  p =new Professor();// constructor is called

Here a variable (p) type Professor is created, using default constructor of class Professor.

If we declare any constructor for a class, than Java does not create a default constructor for that class.

For example,

If we created a constructor which accept parameter or constructor which do not accept parameter, than Java will not declare any default constructor.

Some points to know about constructors are:

  • It does not have a return type.
  • Constructors are not considered as member of the class.
  • The name of the constructor must be same as the name of the class.
  • Keyword public before constructor name shows it can be accessible by other classes too.
  • A constructor supports exception handling.
  • A constructor can be created for each class.
  • A constructor can be overloaded, if having unique signature.
    • For example,
    • Professor p = new Professor(“Jayesh” , “Burhanpur”);
    • Professor p = new Professor(“Jayesh” , “Burhanpur” , 9xxxxx9);

LEAVE A REPLY