Constructor

Constructor

Constructor is a special method of the class whose name is the same as the class name and it runs automatically when an object is created.

Use of Constructor

It is used to initialize instance variables immediately after the creation of an object.

Properties of Constructor

  • It has no return type not even void
  • Its name is same as that of class
  • It runs automatically after creation of an object
  • Compiler automatically creates a default constructor when no constructor is defined

Types of Constructor

  • Constructor which does not take any argument is known as a default constructor. 
  • Default constructor is of two types
  • Created by Programmer
  • Automatically created by the compiler (when no constructor is defined)
  • Constructor that can take arguments is known as parameterized constructor.

Constructor Overloading

Defining two or more constructors in a class is known as Constructor Overloading. All
constructors should have different parameter declarations.

Difference between Constructor and Function

Constructor

Function

Its name is same as class name

Its name is different from class name

It cannot return any value

It can return values

It gets invoked when an object is created

It has to be called explicitly after creation of an object

It is used to initialize instance variables

It is used to perform other tasks


Points to remember

  • Constructor is always defined in public section of the class so that objects can be created in functions of any class.
  • When no constructor is defined, compiler automatically creates a default constructor to initialize instance variables.
  • Default constructor automatically created by the compiler initializes integer variables by 0, floating-point variables by 0.0, boolean variables by false, String and all non-primitive by null.

Post a Comment

0 Comments