To find out whether constructor returns any value or not, let’s learn about a constructor?
In simple terms, the constructor is a special method, which is used to initialize an instance of a class. This special method differs from the actual methods of classes. The name of a constructor is always similar to the name of the class. Below is an example of a constructor:
public class Complex { //This is the constructor Complex(){ } .. }
How Constructor Work?
Consider an example:
public class Student { String name; //Constructor Student(){ this.name = "Hello constructor"; } public static void main(String[] args) { Student obj = new Student(); System.out.println(obj.name); } }
OUTPUT:
Hello constructor
The object is built with the same name as the class name that is Student. The output to this code block is “Hello Constructor,” a pass to the name in the constructor’s initialization. This signifies that as the object obj builds, the constructor is invoked. This keyword represents the current object; here, the object is “obj.” The new keyword generates the object for the class and calls the constructor to define the object’s memory.
Now, let’s see the different types of constructors that you can make. There are three types of constructors:
1. Default Constructor: The objects with no arguments and statements invoke default constructors. All the values remain the same as they were assigned in the data members.
2. No-arg Constructor: The object with no argument but with some statements written inside it invokes the No-argument constructor.
3.Parameterized Constructor: The constructor that has one or more arguments falls under this category.
Does Constructor Return Any Value?
One of the main difference between constructor and method is that constructors do not return any value. In simpler terms, the constructor cannot use the return type. The reason is that you don’t need to return any value.
The purpose of a constructor is to initialize an object. It assigns value to the data members, not return them. So, it does not need to return anything. Moreover, the constructor is called only once.
What would happen if you put the return type to the constructor? For example:
class Student{ int a,b,c; public: int Student(int x){ //this line will show an error as constructor is given a return type a=b=c=x; } };
This will show a compile-time error. This proves that constructors do not return any value.
Nice work ✨