【面試題】構造函數有沒有返回值


  曾經遇到一個面試題——構造函數有沒有返回值?今天調查一番后,給出確切的答案:構造函數沒有返回值。

  我們使用構造函數構造一個String字符串str:

    String str = new String("abc"); 

  這里的new 是調用構造函數,在堆里動態創建一個String對象,並讓str指向這個對象。實際上賦值是因為new關鍵字,而不是()在起作用。
  從語法上講,構造函數不允許有返回值,就算是 void 也不行。可以確定構造函數沒有返回值嗎?

  這是 <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.

We create the object sun refers to using new. The new construct is by far the most common way to create objects (we cover the other ways in Chapter 16). When you create an object with new, you specify the type of object you want to create and any arguments for its construction. The runtime system allocates enough space to store the fields of the object and initializes it in ways you will soon see. When initialization is complete, the runtime system returns a reference to the new object.
  看最后一句話,構造方法是新創建的對象的實例變量缺省初始化以及顯式初始化之后才執行的,也就是說在構造方法調用之前這個對象已經存在了,更談不上構造方法String("abc")返回一個對象引用了。
  對於類似這樣的Java基礎問題,最好的方法當然是去官方的資料尋找答案。於是情不自禁地翻閱了Java 11語言規范的文檔,在章節 8.8 Constructor Declarations 中,關於構造方法的定義有以下說明:
In all other respects, a constructor declaration looks just like a method declaration that has no result (§8.4.5).
  中文意思大概如下:除了沒有返回值,在所有其它方面,定義一個構造器非常像定義一個方法。這從定義的角度告訴我們,構造器沒有返回值;同時也說明構造器不是方法,二者的唯一區別是是否有返回值。

  構造方法就像一種特殊的方法,具有以下特點:

  1. 構造方法的方法名必須與類名相同。
  2. 構造方法沒有返回類型,也不能定義為void,即在方法名前面不聲明方法類型。
  3. 構造方法的主要作用是完成對象的初始化工作,它能夠把定義對象時的參數傳給對象的域。
  4. 構造方法不能由編程人員調用,而要由系統調用。
  5. 一個類可以定義多個構造方法,如果在定義類時沒有定義構造方法,則編譯系統會自動插入一個無參數的默認構造器,這個構造器不執行任何代碼。
  6. 構造方法可以重載,以參數的個數、類型或者排列順序區分。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM