Constructor in Java
It is a special type of method which is used to initialize the object.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.
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
Java Default Constructor
A constructor is called "Default Constructor" when it doesn't have any parameter.
Syntax of default constructor:
Example of default constructor
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of object creation. |
Output:
Bike is created
Q) What is the purpose of default constructor?
Default constructor is used to provide the default values to the object like 0, null etc. depending on the type.
Example of default constructor that displays the default values
Output:
0 null
0 null
0 null 0 null
Explanation:In the above class,you are not creating any constructor so compiler provides you a default constructor.Here 0 and null values are provided by default constructor. |
Java parameterized constructor
A constructor which has a specific number of parameters is called parameterized constructor. |
Why use parameterized constructor?
|
Example of parameterized constructor
In this example, we have created the constructor of Student class that have two parameters. We can have any number of parameters in the constructor. |
Output:
111 Karan 222 Aryan
Sign up here with your email
ConversionConversion EmoticonEmoticon