This tutorial will discuss Java Constructor, why needs for the constructor, the uses of the constructor, and its types, with examples.
A constructor is a block of code that initializes the values of the created object. Also, it is called a constructor is a special type of method in Java.
The constructor is used to initialize the default (initial)values of variables.
We don't need to call the constructor it is automatically called when an object of the corresponding class is created.
Constructors look like methods but when we want to identify the constructor just look at the class name and method name
if both are the same then it is the constructor.
Also, Constructors don't have a return type. And remember one thing all classes have a default constructor. even if you have not created yourself the compiler creates by itself.
In java, memory is allocated for objects at the time of constructor calls.
If you create an object by using a new keyword the same number of times the constructor of the class will be called.
If the class doesn't have is any default constructor then the compiler creates one default constructor.
Let's point out some important points about the constructor.
- Constructor is a special method used to initialize objects.
- The name of the class same as a constructor's name.
- The constructor doesn't have a return type.
- We can declare the constructor as public, private, protected, and default.
- We can't declare the constructor as static, abstract, and final.
- In java constructor overloading is possible.
- We can not override, the inherited constructor in java.
- The default constructor is used to initialize default values.
class class-name
{
public constructor-name()
{
// code in constructor
}
// other code
}
Example
class Student
{
public Student(int id, String name)
{
this.id=id;
this.name=name;
}
}
Types of Constructor
1) default constructor
2) parameterized constructor
1) default constructor
The constructor which is don't have any parameters.
Ex.
public Hello()
{
// constructor body
}
2) Parameterized constructor
The constructor has some number of parameters passed in the constructor called a Parameterized constructor.
Ex.
public Student(int id, String name)
{
this.id=id;
this.name=name;
}