在《Thinking in Java》中文Quanke翻譯版本第四章初始化和清除,原書第五章Initialization&Cleanup中。關於用構建器自動初始化有以下描述:html
構建器有助於消除大量涉及類的問題,並使代碼更易閱讀。例如在前述的代碼段中,咱們並未看到對initialize()方法的明確調用——那些方法在概念上獨立於定義內容。在Java中,定義和初始化屬於統一的概念——二者缺一不可。 構建器屬於一種較特殊的方法類型,由於它沒有返回值。這與void返回值存在着明顯的區別。對於void返回值,儘管方法自己不會自動返回什麼,但仍然能夠讓它返回另外一些東西。構建器則不一樣,它不只什麼也不會自動返回,並且根本不能有任何選擇。若存在一個返回值,並且假設咱們能夠自行選擇返回內容,那麼編譯器多少要知道如何對那個返回值做什麼樣的處理。java
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.express
另外在《The Java Programming Language》oracle
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.ide
大體這樣寫,儘管方法自己不會自動返回什麼,但仍然能夠讓它返回另外一些東西。關於構建器有返回值的證據無非是這樣:翻譯
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對象的時候:code
tree t = new Tree(12); // 12英尺高的樹
這樣來看構建Tree對象的時候的確返回了內容。htm
首先須要瞭解new
這個關鍵字但到底作了什麼?由於篇幅有限,能夠訪問ORACLE官方的JavaDocumention(點擊JavaDocumention能夠瀏覽英文原版),翻譯版本(點擊翻譯版本文本瀏覽)對象