Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How can a constructor return a value? [duplicate]

$ cat Const.java 
public class Const {
    String Const(String hello) {
        return hello; 
 }
 public static void main(String[] args) {
     System.out.println(new Const("Hello!"));
 }
}
$ javac Const.java 
Const.java:7: cannot find symbol
symbol  : constructor Const(java.lang.String)
location: class Const
  System.out.println(new Const("Hello!"));
                     ^
1 error
like image 400
hhh Avatar asked Apr 04 '10 11:04

hhh


People also ask

Can a constructor return a value in Java?

No, constructor does not return any value. While declaring a constructor you will not have anything like return type. In general, Constructor is implicitly called at the time of instantiation. And it is not a method, its sole purpose is to initialize the instance variables.

Can a constructor declare a return value?

A constructor can not return a value because a constructor implicitly returns the reference ID of an object, and since a constructor is also a method and a method can't return more than one values.

Can constructor have a return type in Java?

No, constructor does not have any return type in Java. Constructor looks like method but it is not. It does not have a return type and its name is same as the class name. Mostly it is used to instantiate the instance variables of a class.

Can constructors return things?

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.


1 Answers

What you've defined isn't actually a constructor, but a method called Const. If you changed your code to something like this, it would work:

Const c = new Const();
System.out.println( c.Const( "Hello!" ) );

If no specific constructor is explicitly defined, the compiler automatically creates a no-argument constructor.

like image 65
Ash Avatar answered Sep 21 '22 17:09

Ash