Java:构造函数如何返回值? [英] Java: How can a constructor return a value?
本文介绍了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
的方法。如果你改变你的代码到这样,它会工作:
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.
这篇关于Java:构造函数如何返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文