Home » Java constructor returns a value, but what

Java constructor returns a value, but what

by Online Tutorials Library

Java constructor returns a value, but what?

The Constructor is a block of code that is used to initialize the instance variables within the class. The default constructor in a class is invoked at the time of object creation. However, we can also use a parameterized constructor to initialize the data members with a customized value within a class. Therefore, the constructors in Java are of two types:

  1. Default Constructor
  2. Parameterized Constructor

In a Java program, if we do not use any constructor, the Java compiler itself invokes a default constructor through the object class to initialize the data members used within the class. Consider the following example.

In the above example, the default values of the Student class’s instance variables, i.e., id and name (0 and null), get printed.

However, in the above example, we could have used an explicit default constructor with the same name as a class, but that is not an efficient way to use a constructor since it invokes an implicit constructor for our use.

We can also use a parameterized constructor in class Student if we need to initialize the id and name of the student with some initial value. Consider the following example.

Here, the parametrized Constructor itself initializes the values to the variables with the values provided at object creation.

What does Constructor return?

Well, this is the most important and million-dollar question about the Java constructors. However, constructors are the special type of methods defined with the same name as the class. Like a method, the Constructor can also be overloaded.

In general, the java constructor doesn’t return any specific value, which can directly affect the code because it is not like a normal method used in the java code. Also, the fact that a constructor is not directly called by the java code infect is called by the memory allocation and object initialization code at runtime.

However, a method’s work is to return the result to the caller, whereas the Constructor is more responsible for assigning the initial values to the data members of the class. Although the Constructor can also contain the number of instructions inside it, it can’t return the result of statements.

Here, we should also notice that a constructor returns the instance created by the new keyword in our java code. Consider the following example.


You may also like