Constructor is a block of code that initializes the newly created object. A constructor resembles an instance method in java but it’s not a method as it doesn’t have a return type. In short constructor and method are different(More on this at the end of this guide). People often refer constructor as special type of method in Java.
public class MyClass
{ //This is the constructor MyClass()
{ } .. }
Types –
There are three types of constructors: Default, No-arg constructor and Parameterized.
How does a constructor work
To understand the working of constructor, lets take an example.
lets say we have a class MyClass.
When we create the object of MyClass like this:
MyClass obj = new MyClass()
The new keyword here creates the object of class MyClass and invokes the constructor to initialize this newly created object.
A simple constructor program in java
public class Hello
{ String name; //Constructor Hello(){ this.name = "constructor"; } public static void main(String[] args) { Hello obj = new Hello(); System.out.println(obj.name); } }
Output:
constructor
Example: no-argument constructor
class Demo { public Demo() { System.out.println("This is a no argument constructor"); } public static void main(String args[]) { new Demo(); } }
Output:
This is a no argument constructor
Parameterized constructor
Constructor with arguments(or you can say parameters) is known as Parameterized constructor.
Example: parameterized constructor
public class Employee { int empId; String empName; //parameterized constructor with two parameters Employee(int id, String name){ this.empId = id; this.empName = name; } void info(){ System.out.println("Id: "+empId+" Name: "+empName); } public static void main(String args[]){ Employee obj1 = new Employee(10245,"Chaitanya"); Employee obj2 = new Employee(92232,"Negan"); obj1.info(); obj2.info(); } }
Output:
Id: 10245 Name: Chaitanya Id: 92232 Name: Negan
Java Copy Constructor
A copy constructor is used for copying the values of one object to another object.
class JavaExample{ String web; JavaExample(String w){ web = w; } /* This is the Copy Constructor, it * copies the values of one object * to the another object (the object * that invokes this constructor) */ JavaExample(JavaExample je){ web = je.web; } void disp(){ System.out.println("EX: "+web); } public static void main(String args[]){ JavaExample obj1 = new JavaExample("constructor "); /* Passing the object as an argument to the constructor * This will invoke the copy constructor */ JavaExample obj2 = new JavaExample(obj1); obj1.disp(); obj2.disp(); } }
Output:
EX: constructor EX: constructor
Constructor Overloading
Constructor overloading is a concept of having more than one constructor with different parameters list, in such a way so that each constructor performs a different task.