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. Allconstructors should have different parameter declarations.
Difference between Constructor and Function
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.
0 Comments
Please don't enter any spam link in comment box.
Emoji