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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2574276/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 09:24:07  来源:igfitidea点击:

Java: How can a constructor return a value?

javaconstructorreturn-value

提问by hhh

$ 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

采纳答案by Ash

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. 如果您将代码更改为这样的内容,它将起作用:

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.

如果没有明确定义特定的构造函数,编译器会自动创建一个无参数的构造函数。

回答by Bozhidar Batsov

The constructor cannot return a value. That's final. It the same sense - it cannot have a return type and that's why you're getting the compile error. You may say that the return value is always implicitly the object created by the constructor.

构造函数不能返回值。那是最终的。意义相同 - 它不能有返回类型,这就是您收到编译错误的原因。你可能会说返回值总是隐式地是构造函数创建的对象。

回答by Mohammad Kotb

Actually Constructor in a java class can't return a value it must be in the following form

实际上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
 }
}

check these links http://leepoint.net/notes-java/oop/constructors/constructor.htmlhttp://java.sun.com/docs/books/tutorial/java/javaOO/constructors.html

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

回答by Venemo

A constructor can't have a return value like a "normal" function. It is called when an istance of the class in question is created. It is used to perform the initialization of that instance.

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

回答by scherand

Constructors cannot return a value; they return the constructed object, so to speak.

构造函数不能返回值;他们返回构造的对象,可以这么说。

You get an error because the compiler is looking for a constructor that takes a string as its argument. Since you did notdeclare a constructor the only constructor available is the default constructor that does not take any argument.

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

Why do I say you did not declare a constructor? Because as soon as you declare a return value/type for your method it is not a constructor anymore but a regular method.

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

From the Java Documentation:

Java 文档

A class contains constructors that are invoked to create objects from the class blueprint. Constructor declarations look like method declarations—except that they use the name of the class and have no return type.

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

If you elaborate what you are trying to achieve someone might be able to tell you how you can get to that goal.

如果您详细说明您要实现的目标,有人可能会告诉您如何实现该目标。

回答by Arthur

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());
  }
}

回答by Edd

I think the best way to produce the effect you want would be the following:

我认为产生您想要的效果的最佳方法如下:

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!"));
    }
}

This replaces the public String Const()method you used previously, and by overriding the public String toString()method of Object(Which all Java classes inherit from) the String value of the object is printed correctly when you want to print the object, so your main method remains unchanged.

这将替换public String Const()您之前使用的方法,并通过覆盖(所有 Java 类都继承自)的public String toString()方法,Object当您要打印对象时,将正确打印对象的 String 值,因此您的 main 方法保持不变。

回答by Ajendra Chaurasia

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. So we say explicitely constructor does not have a return value.

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

回答by amphibient

Many great answers already. I would just like to add that, if you want to get some return code separate from the object itself as a result of invoking a constructor, you can wrap the constructor in a factory methodwhich, upon creation, could for example do some data validation within the constructed object and return a booleandepending on the outcome.

已经有很多很棒的答案了。我只想补充一点,如果您想在调用构造函数时获得一些与对象本身分离的返回代码,您可以将构造函数包装在 afactory method中,例如,在创建时,可以在其中进行一些数据验证构造对象并boolean根据结果返回 a 。

回答by Adrian Powell

To pass back a value from a constructor - just pass in an array as a parameter. To illustrate the principle:

要从构造函数传回值 - 只需传入一个数组作为参数。为了说明原理:

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