What is Constructor in Java
Constructors in Java are special types of methods that are used to initialize the objects of the class. Constructors are called at the time of object creation of the class. Just like methods, although they hold a set of lines of code, they are quite different from them. Constructors have the same name as the Java class, but it does not have any return type. In Java, a new() keyword to used to create an object and every time a new object is created and one constructor is called. The constructor is called after the memory is allocated to the object. At the time of object creation, constructors are used to initialise class variables’ values to either default or the desired ones.
If the user does not create any constructor in the program, Java itself creates a default constructor for it and assign default values to the different objects like for numeric default value is 0, for a character (‘\0’) and reference variables as null. Like methods, constructors can be overloaded, i.e. a single class can have many constructors if all of them have a unique signature.
The basic syntax of constructor in Java is given below:
Syntax:
public class Student() // name of the class
{
. . . .
. . . .
. . . .
Student() // this is Constructor with the same name of class
{
. . .
. . .
}
new Student(); // object creation and value initialization
}
In the above syntax, Student() is the name of the constructor, which is the same as the name of the class and the objects in Java are created using the keyword new.
How does Constructor Work in Java?
To understand the working of Constructors in Java, let’s take an example given below:
Code:
public class Student()
{
int rollno;
String name;
Student(int rollno, String name)
{
this.rollno = rollno;
this.name = name;
}
public static void main(String[] args)
{
Student st = new Student(12, 'Ananya');
System.out.println("Student name = "+ st.name + "Student rollno = "+st.rollno);
}
}
Output:
In the above example, we have instance variables (class variables). roll no and name and st Is the name of the object created of the class Student. When the object it is created, it invokes the constructor Student and initializes the class variables with the roll no value as 12 and name as ‘Ananya’; otherwise, default values like 0 for rollno and null for the name will get assigned to the variables. Hence after assigning the values and printing them, the student name is printed as Ananya and the Student roll no as 12.
Types of Constructors in Java
There are 2 types of constructors in Java based on parameters:
1. Non-parameterized / No arguments Constructor
When we do not pass arguments in the constructor, that constructor is known as a non-parameterized or no-argument constructor. When the programmer does not define any constructor in the Java program, the Java compiler itself adds a constructor, known as the default constructor, which provides default values to the object like 0, null, etc. The default constructor is no special type of constructor but falls in the category of no arguments constructor.
Example (Default Constructor)
Code:
public class Hello()
{
String name;
void display() //method to display name the value of variables
{
System.out.println("name is" +name);
}
}
public class HelloMain()
{
public static void main(String[] args)
{
Hello h1 = new Hello();
h1.display();
}
}
Output:
In the above example, this is no constructor defined by the programmer, so the compiler will treat this program as:
Code:
public class Hello()
{
String name;
Hello() //default constructor created by compiler
{
name = null
}
void display()
{
System.out.println("name is" +name);
}
}
public class HelloMain()
{
public static void main(String[] args)
{
Hello h1 = new Hello();
h1.display();
}
}
Example (Non-Parameterized Constructor)
Code:
public DemoProgram() // class
{
DemoProgram() // constructor with no arguments
{
System.out.println("Hello this is just an example of no-arg constructor");
}
public static void main(String[] args)
{
new DermoProgram();
}
}
Output:
As in the above example, for the constructor DemoProgram(), there are no arguments passed, only the message is printed, and hence it is known as the No-argument constructor.
2. Parameterized Constructor
Parameterized constructors are those constructors in which we pass the arguments or parameters. In this constructor, values are passed at the time of object creation.
Example (Parameterized Constructors)
Code:
public class Animal()
{
int legs;
String sound;
Animal(int legs, String sound) // parameterized constructor
{
this.legs = legs; // values with get initialize of what is passed while object crea-this.sound = sound; // tion, i.e. (4, “bow bow”)
}
void display() // method to display the values
{
System.out.println("Legs are "+legs+"Sound is "+sound);
}
}
class AnimalPlanet()
{
public static void main(String[] args)
{
Animal an = new Animal(4, "bow bow");
an.display();
}
}
Output:
In the above example, value 4 is assigned to the legs, and the string “bow bow” is assigned to the sound in the constructor Animal. So when the method display is called, both the values get printed in the output.
Important Points to Remember
- Every class has a constructor, whether the programmer creates it or not.
- The constructor name should be the same as the class name.
- The constructor has no return type, unlike methods.
- this() and super() keywords must be the first statement in a constructor.
- Like methods, constructors can be overloaded.
- Constructors can not be overridden.
- One constructor can invoke another constructor of the same class using the keyword this().
- Access specifiers/ modifiers can be applied before the constructor’s name to declare its scope in a class.
- In Java, a constructor can never be static, final, abstract, and Synchronized.
Conclusion
Constructors play an important role when it comes to working with the Java programming language. One must need to understand the full concepts of Constructor, various types of Constructors, Constructor Chaining, and the super() keyword used to call the parent constructor to work according to the specific scenario. Though working with constructors in Java is very easy, like working with methods, a few specific points should be learned thoroughly.
Recommended Articles
This is a guide to Constructor in Java. Here we discuss how constructors work in Java and the types and examples with appropriate code implementation. You can also go through our suggested articles to learn more –