Java构建器(Constructor)返回了什么?

1. 构建器Constructor的返回值?

1.1为什么会有这个问题?

在《Thinking in Java》中文Quanke翻译版本第四章初始化和清除,原书第五章Initialization&Cleanup中。关于用构建器自动初始化有如下描述:

构建器有助于消除大量涉及类的问题,并使代码更易阅读。例如在前述的代码段中,我们并未看到对initialize()方法的明确调用——那些方法在概念上独立于定义内容。在Java中,定义和初始化属于统一的概念——两者缺一不可。 构建器属于一种较特殊的方法类型,因为它没有返回值。这与void返回值存在着明显的区别。对于void返回值,尽管方法本身不会自动返回什么,但仍然可以让它返回另一些东西。构建器则不同,它不仅什么也不会自动返回,而且根本不能有任何选择。若存在一个返回值,而且假设我们可以自行选择返回内容,那么编译器多少要知道如何对那个返回值作什么样的处理。

Constructors eliminate a large class of problems and make the code easier to read. In the preceding code fragment, for example, you don’t see an explicit call to some initialize( ) method that is conceptually separate from creation. In Java, creation and initialization are unified concepts—you can’t have one without the other.
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.


另外在《The Java Programming Language》

For purposes other than simple initialization, classes can have constructors. Constructors are blocks of statements that can be used to initialize an object before the reference to the object is returned by new. Constructors have the same name as the class they initialize. Like methods, they take zero or more arguments, but constructors are not methods and thus have no return type. Arguments, if any, are provided between the parentheses that follow the type name when the object is created with new. Constructors are invoked after the instance variables of a newly created object of the class have been assigned their default initial values and after their explicit initializers are executed.

大致这样写,尽管方法本身不会自动返回什么,但仍然可以让它返回另一些东西。关于构建器有返回值的证据无非是这样:

class Rock {
  Rock(int i) {
  System.out.println("Creating Rock number " + i);
  }
}

public class SimpleConstructor {
  public static void main(String[] args) {
  for(int i = 0; i < 10; i++)
  new Rock(i);
  }
}

当用new来构建一个Tree对象的时候:

tree t = new Tree(12); // 12英尺高的树

这样来看构建Tree对象的时候的确返回了内容。

首先需要了解new这个关键字但到底做了什么?因为篇幅有限,可以访问ORACLE官方的JavaDocumention(点击JavaDocumention可以浏览英文原版),翻译版本(点击翻译版本文本浏览)


posted @ 2018-11-22 16:12  ED_Reagan  阅读(316)  评论(0编辑  收藏  举报