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 classMyClass{ public static void main(String[] args) {// creating an object called objMyClassobj= new MyClass(); } } The Code Compiler interprets : public classMyClass{//default constructorMyClass() { } public static void main(String[] args) {// creating an object called objMyClassobj= 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 classMyClass{MyClass() { System.out.println("Constructor is called !"); } public static void main(String[] args) {// creating an objects // constructors invoked when objects createdMyClassobj= new MyClass(); MyClassobj1= 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 .
classOtherClass{ intid; OtherClass(intid1) {// this keyword refers to id of current objectthis.id=id1; System.out.println("The id entered is:" +id1); } } public classMyClass{ public static void main(String[] args) { OtherClassemp= new OtherClass(5); } }
Output:-
The id entered is: 5
Lets look at another program consisting a constructor of two parameters String empName , int empId.
classOtherClass{ intid; Stringname;OtherClass(intempId, StringempName) {this.id=empId;this.name=empName; System.out.println("The ID of" +empName+ "is" +empId+ "."); } } public classMyClass{ public static void main(String[] args) { OtherClassemp= new OtherClass(76454, "Bob"); OtherClassemp1= new OtherClass(76455, "John"); } }
Output:-
The ID of Bob is 76454.
The ID of John is 76455.

