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

$ 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 

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

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

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

构造函数不能返回值; 他们可以回归构造的物体。

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

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

从Java文档 :

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

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

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

 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 } } 

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

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

很多很棒的答案。 我想补充一点,如果你想通过调用构造函数将一些返回代码与对象本身分开,你可以将构造函数包装在一个factory method中,该factory method在创建时可以进行一些数据validation。在构造的对象中并根据结果返回一个boolean

构造函数不能返回值。 那是最后的。 它有同样的意义 – 它不能有返回类型,这就是你得到编译错误的原因。 您可能会说返回值始终隐含在构造函数创建的对象中。

构造函数不能具有类似“普通”函数的返回值。 当创建所讨论的类的istance时调用它。 它用于执行该实例的初始化。

我认为产生你想要的效果的最好方法是:

 public class Const { private String str; public Const(String hello) { str = hello; } public String toString() { return str; } public static void main(String[] args) { System.out.println(new Const("Hello!")); } } 

这将替换您之前使用的public String Const()方法,并通过覆盖Objectpublic String toString()方法(所有Java类inheritance自),当您要打印对象时,正确打印对象的String值,所以你的主要方法保持不变。

 public class Const { private String myVar; public Const(String s) { myVar = s; } public String getMyString() { return myVar; } public static void main(String[] args) { Const myConst = new Const("MyStringHere"); System.out.println(myConst.getMyString()); } } 

从构造函数传回一个值 – 只需将数组作为参数传入。 说明原则:

 Test() { Boolean[] flag = new Boolean[1]; flag[0] = false; new MyClass(flag); System.out.println(flag[0]); // Will output 'true' } class MyClass { MyClass(Boolean[] flag) { // Do some work here, then set flag[0] to show the status flag[0] = true; } } 
 /************************************************ Put the return value as a private data member, which gets set in the constructor. You will need a public getter to retrieve the return value post construction ******************************************************/ class MyClass { private Boolean boolReturnVal; public Boolean GetReturnVal() { return(boolReturnVal); } MyClass() // constructor with possibly args { //sets the return value boolReturnVal } public static void main(String args[]) { MyClass myClass = new MyClass(); if (myClass.GetReturnVal()) { //success } } 

}