Java:构造函数如何返回值?

hhh*_*hhh 16 java constructor return-value

$ 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
Run Code Online (Sandbox Code Playgroud)

Ash*_*Ash 25

您定义的实际上不是构造函数,而是一个名为的方法Const.如果您将代码更改为此类代码,它将起作用:

Const c = new Const();
System.out.println( c.Const( "Hello!" ) );
Run Code Online (Sandbox Code Playgroud)

如果未显式定义特定构造函数,则编译器会自动创建无参数构造函数.


sch*_*and 23

构造函数不能返回值; 可以这么说,它们可以返回构造的物体.

您收到错误,因为编译器正在查找以字符串作为参数的构造函数.既然你也没有声明构造唯一可用的构造函数是不带任何参数的默认构造函数.

为什么我说你没有声明构造函数?因为只要为方法声明返回值/类型,它就不再是构造函数,而是常规方法.

Java文档:

类包含被调用以从类蓝图创建对象的构造函数.构造函数声明看起来像方法声明 - 除了它们使用类的名称并且没有返回类型.

如果你详细说明你想要实现的目标,那么有人可能会告诉你如何实现这一目标.


Moh*_*otb 9

实际上,java类中的构造函数不能返回必须采用以下形式的值

public class Test {
 public Test(/*here the params*/) {
   //this is a constructor
   //just make some operations when you want to create an object of this class
 }
}
Run Code Online (Sandbox Code Playgroud)

检查这些链接 http://leepoint.net/notes-java/oop/constructors/constructor.html http://java.sun.com/docs/books/tutorial/java/javaOO/constructors.html


小智 5

构造函数不能返回值,因为构造函数隐式返回对象的引用ID,并且构造函数也是方法,并且方法不能返回多个值.所以我们说explicitely构造函数没有返回值.