Java Constructor (Part 1)
Java Constructor
Constructor in Java is a special-member function. It is used to initialize objects. Constructors are called when objects are created. If the user does not create a constructor , Java has a pre-built constructor that is called when created objects.
Rules for creating a Constructor:
▪ The name of the constructor must match the class name.
▪ We can add parameters to a constructor.
▪ The constructor cannot have a return type i.e it is by default void. But we can write return statement in it as it can return class , we will learn about this in future tutorials.
There are 3 types of constructors:
1. Default Constructor
If user does not implement a constructor , then when an object is created the Java compiler inserts a default (pre-built) constructor. It does not contain any code in it.
eg:-
Code We Write :
public class
MyClass
{ public static void main(String[] args) {
// creating an object called obj
MyClass
obj
= new MyClass(); } } The Code Compiler interprets : public class
MyClass
{
//default constructor
MyClass
() { } public static void main(String[] args) {
// creating an object called obj
MyClass
obj
= new MyClass(); } }
If you implement a constructor then the default constructor is no longer received.
2. No-argument Constructor
No-arg constructor is a constructor with no parameters/arguments . It is like a default constructor but only user-defined with a block of code.
eg:-
public class
MyClass
{
MyClass
() { System.out.println("
Constructor is called !
"); } public static void main(String[] args) {
// creating an objects // constructors invoked when objects created
MyClass
obj
= new MyClass(); MyClass
obj1
= new MyClass(); } }
Output:-
Constructor is called !
Constructor is called !
Here when we create two objects obj , obj1 the constructor is invoked two times.
3. Parameterized Constructor
A constructor with parameters/argument is called a parameterized constructor. One can define a number of parameters as per users need.
Here I am defining a constructor with one parameter i.e int id .
class
OtherClass
{ int
id
; OtherClass(int
id1
) {
// this keyword refers to id of current object
this
.
id
=
id1
; System.out.println("
The id entered is:
" +
id1
); } } public class
MyClass
{ public static void main(String[] args) { OtherClass
emp
= new OtherClass(5); } }
Output:-
The id entered is: 5
Lets look at another program consisting a constructor of two parameters String empName , int empId.
class
OtherClass
{ int
id
; String
name
;
OtherClass
(int
empId
, String
empName
) {
this
.
id
=
empId
;
this
.
name
=
empName
; System.out.println("
The ID of
" +
empName
+ "
is
" +
empId
+ "
.
"); } } public class
MyClass
{ public static void main(String[] args) { OtherClass
emp
= new OtherClass(76454, "
Bob
"); OtherClass
emp1
= new OtherClass(76455, "
John
"); } }
Output:-
The ID of Bob is 76454.
The ID of John is 76455.