Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does a constructor return in Java?

People also ask

What does a constructor return?

No, constructor does not return any value. While declaring a constructor you will not have anything like return type.

What is the return type of a constructor in Java?

A constructor doesn't have any return type. The data type of the value retuned by a method may vary, return type of a method indicates this value. A constructor doesn't return any values explicitly, it returns the instance of the class to which it belongs.


This is a little confusing: constructors indeed do not return a value; it is operator new that does. However, constructors are always used with a new*, so it looks like they always return a value.


* This is a slight simplification: you can use a constructor without new if you go through reflection. However, the same mechanisms will be in play.

A constructor returns a new instance of the class it belongs to, even if it doesn't have an explicit return statement.


I think the confusion is purely notational. When you declare a constructor, you do it like so:

public class Foo {
    public Foo() {}
}

Here, there's no explicit return value.

However, when you instantiate an object, the syntax is as follows:

Foo foo = new Foo();

This creates a new object by allocating memory and calling the constructor. Here, the result is clearly an instance of Foo.

One way to reconcile the apparently conflicting notation is by thinking of a constructor as returning the object being constructed, but doing so implicitly.


Constructors are SPECIAL METHODS. Well the Basic difference in Constructors and Methods is that

Constructor

  • Have same name as that of Class
  • does not have a return type
  • Can be Overloaded but not Overridden.

whereas

Methods

  • May or may not have same name as that of Class.
  • have return type
  • Can be Overloaded and Overridden.

Syntax For Methods:
AccessModifier ReturnType Class(...)
EG: public static void main(String []args)

Syntax For Constructors:
AccessModifier No ReturnType Class(...)
EG: public static main(String []args)

Please Note:

Java is a strongly typed language, so each function has its return type, and constructor always returns an instance of the class.


so, far i am concern constructor return the reference id to reference variable of that class. take an example:

class demo
{
    demo{}
}
class demo1
{
    public static void main(String as[])
    {
        demo d = new demo();
        System.out.println(d);
    }
}

output: demo@7d4991ad it is the reference id of the object 'd' of class demo which is returned by the constructor. if u will not define your constructor then jvm will get this id from default constructor.

you can cross check it by this line: System.out.println(new demo()); output: demo@1b6d3586. since every object has its separate heap area in memory so reference id of each object also vary.