答案是不能,没有返回值和返回值为void是两种概念
《Thinking in java》这本书里头是这么解释的:
"The constructor is an unusual type of method because it has no return value. This is distinctly different from a void return value, in which the method returns nothing but you still have the option to make it return something else. Constructors return nothing and you don’t have an option (the new expression does return a reference to the newly created object, but the constructor itself has no return value). If there were a return value, and if you could select your own, the compiler would somehow need to know what to do with that return value."
总结下原因就是,构造函数是完全不能够返回值的,我们没有选择。而void是我们有选择的不返回一个值。只有这样区分了,虚拟机才知道哪个是构造函数。
我们可以写段代码来看返回类型为void时是否能作为构造函数被调用:- public class ConstructorTest
- {
- public static void main(String[] args)
- {
- Test test = new Test();
- System.out.println("x="+test.x);
- }
- }
- class Test
- {
- void Test()
- {
- x=10;
- }
-
- int x;
- }
复制代码 输出结果为:x=0
由此我们看来,实例化Test时并没有调用void Test()这个方法使x被赋值为10。也就是说,加了void就不是构造函数了。 |