Java constructors or constructors in Java is a terminology used to construct something in our programs. A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes.
What are Constructors in Java?
In Java, Constructor is a block of codes similar to the method. It is called when an instance of the class is created. At the time of calling the constructor, memory for the object is allocated in the memory. It is a special type of method that is used to initialize the object. Every time an object is created using the new() keyword, at least one constructor is called.
Example
Java
// Java Program to demonstrate // Constructor import java.io.*; class Geeks { // Constructor Geeks() { super (); System.out.println( "Constructor Called" ); } // main function public static void main(String[] args) { Geeks geek = new Geeks(); } } |
Constructor Called
Note: It is not necessary to write a constructor for a class. It is because the java compiler creates a default constructor (constructor with no arguments) if your class doesn’t have any.
How Java Constructors are Different From Java Methods?
- Constructors must have the same name as the class within which it is defined it is not necessary for the method in Java.
- Constructors do not return any type while method(s) have the return type or void if does not return any value.
- Constructors are called only once at the time of Object creation while method(s) can be called any number of times.
Now let us come up with the syntax for the constructor being invoked at the time of object or instance creation.
class Geek { ....... // A Constructor Geek() { } ....... } // We can create an object of the above class // using the below statement. This statement // calls above constructor. Geek obj = new Geek();
The first line of a constructor is a call to super() or this(), (a call to a constructor of a super-class or an overloaded constructor), if you don’t type in the call to super in your constructor the compiler will provide you with a non-argument call to super at the first line of your code, the super constructor must be called to create an object:
If you think your class is not a subclass it actually is, every class in Java is the subclass of a class object even if you don’t say extends object in your class definition.
Need of Constructors in Java
Think of a Box. If we talk about a box class then it will have some class variables (say length, breadth, and height). But when it comes to creating its object(i.e Box will now exist in the computer’s memory), then can a box be there with no value defined for its dimensions? The answer is No.
So constructors are used to assign values to the class variables at the time of object creation, either explicitly done by the programmer or by Java itself (default constructor).
When Constructor is called?
Each time an object is created using a new() keyword, at least one constructor (it could be the default constructor) is invoked to assign initial values to the data members of the same class. Rules for writing constructors are as follows:
- The constructor(s) of a class must have the same name as the class name in which it resides.
- A constructor in Java can not be abstract, final, static, or Synchronized.
- Access modifiers can be used in constructor declaration to control its access i.e which other class can call the constructor.
So by far, we have learned constructors are used to initialize the object’s state. Like methods, a constructor also contains a collection of statements(i.e. instructions) that are executed at the time of Object creation.
Types of Constructors in Java
Now is the correct time to discuss the types of the constructor, so primarily there are three types of constructors in Java are mentioned below:
- Default Constructor
- Parameterized Constructor
- Copy Constructor
1. Default Constructor in Java
A constructor that has no parameters is known as default the constructor. A default constructor is invisible. And if we write a constructor with no arguments, the compiler does not create a default constructor. It is taken out. It is being overloaded and called a parameterized constructor. The default constructor changed into the parameterized constructor. But Parameterized constructor can’t change the default constructor.
Example:
Java
// Java Program to demonstrate // Default Constructor import java.io.*; // Driver class class GFG { // Default Constructor GFG() { System.out.println( "Default constructor" ); } // Driver function public static void main(String[] args) { GFG hello = new GFG(); } } |
Default constructor
Note: Default constructor provides the default values to the object like 0, null, etc. depending on the type.
2. Parameterized Constructor in Java
A constructor that has parameters is known as parameterized constructor. If we want to initialize fields of the class with our own values, then use a parameterized constructor.
Example:
Java
// Java Program for Parameterized Constructor import java.io.*; class Geek { // data members of the class. String name; int id; Geek(String name, int id) { this .name = name; this .id = id; } } class GFG { public static void main(String[] args) { // This would invoke the parameterized constructor. Geek geek1 = new Geek( "avinash" , 68 ); System.out.println( "GeekName :" + geek1.name + " and GeekId :" + geek1.id); } } |
GeekName :avinash and GeekId :68
Remember: Does constructor return any value?
There are no “return value” statements in the constructor, but the constructor returns the current class instance. We can write ‘return’ inside a constructor.
Now the most important topic that comes into play is the strong incorporation of OOPS with constructors known as constructor overloading. Just like methods, we can overload constructors for creating objects in different ways. The compiler differentiates constructors on the basis of the number of parameters, types of parameters, and order of the parameters.
Example:
Java
// Java Program to illustrate constructor overloading // using same task (addition operation ) for different // types of arguments. import java.io.*; class Geek { // constructor with one argument Geek(String name) { System.out.println( "Constructor with one " + "argument - String : " + name); } // constructor with two arguments Geek(String name, int age) { System.out.println( "Constructor with two arguments : " + " String and Integer : " + name + " " + age); } // Constructor with one argument but with different // type than previous.. Geek( long id) { System.out.println( "Constructor with one argument : " + "Long : " + id); } } class GFG { public static void main(String[] args) { // Creating the objects of the class named 'Geek' // by passing different arguments // Invoke the constructor with one argument of // type 'String'. Geek geek2 = new Geek( "Shikhar" ); // Invoke the constructor with two arguments Geek geek3 = new Geek( "Dharmesh" , 26 ); // Invoke the constructor with one argument of // type 'Long'. Geek geek4 = new Geek( 325614567 ); } } |
Constructor with one argument - String : Shikhar Constructor with two arguments : String and Integer : Dharmesh 26 Constructor with one argument : Long : 325614567
3. Copy Constructor in Java
Unlike other constructors copy constructor is passed with another object which copies the data available from the passed object to the newly created object.
Example:
Java
// Java Program for Copy Constructor import java.io.*; class Geek { // data members of the class. String name; int id; // Parameterized Constructor Geek(String name, int id) { this .name = name; this .id = id; } // Copy Constructor Geek(Geek obj2) { this .name = obj2.name; this .id = obj2.id; } } class GFG { public static void main(String[] args) { // This would invoke the parameterized constructor. System.out.println( "First Object" ); Geek geek1 = new Geek( "avinash" , 68 ); System.out.println( "GeekName :" + geek1.name + " and GeekId :" + geek1.id); System.out.println(); // This would invoke the copy constructor. Geek geek2 = new Geek(geek1); System.out.println( "Copy Constructor used Second Object" ); System.out.println( "GeekName :" + geek2.name + " and GeekId :" + geek2.id); } } |
First Object GeekName :avinash and GeekId :68 Copy Constructor used Second Object GeekName :avinash and GeekId :68
To know deep down about constructors there are two concepts been widely used as listed below:
Frequently Asked Questions(FAQs)
Q1. What is a constructor in Java?
Ans:
A constructor in Java is a special method used to initialize objects.
Q2. Can a Java constructor be private?
Ans:
Yes, a constructor can be declared private. A private constructor is used in restricting object creation.
This article is contributed by Nitsdheerendra. If you like Lazyroar and would like to contribute, you can also write an article using write.geeksforgeeks.org. See your article appearing on the Lazyroar main page and help other Geeks. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.