Constructor in Java
In Java, constructor is a block of codes similar to method. It is called when an instance of object is created and memory is allocated for the object.
It is a special type of method which is used to initialize the object.
Note: It is called constructor because it constructs the values at the time of object creation. It is not necessary to write a constructor for a class. It is because java compiler creates a default constructor if your class doesn't have any.
Rules for creating java constructor
There are basically two rules defined for the constructor.
- Constructor name must be same as its class name
- Constructor must have no explicit return type
Types of java constructors
There are two types of constructors in java:
- Default constructor (no-arg constructor)
- Parameterized constructor
loading...
No comments: