2015-07-10 80 views
0

我剛開始學習Java,來到從Java第九版數量銳減Schildt參數方法和參數的構造函數[第6章]的這個話題,何時使用參數化方法VS參數的構造函數在Java中

我明白瞭如何聲明他們和他們是如何工作的,但我對他們的用法感到困惑,何時使用參數化方法以及何時使用參數化構造函數?

請給我一個簡單的比喻的例子。

回答

0

首先您應該瞭解構造函數的實際含義。

您可以將「構造函數」看作是每當爲類創建對象時都會調用的函數。在類中可以有許多實例變量,即該類的每個對象都有自己的實例變量副本。因此,無論何時使用new ClassName (args)語句創建新對象,都可以在構造函數中初始化該對象的實例變量的值,因爲無論何時您實例化對象時都會首先調用該對象的實例變量值。記住構造函數在創建對象時只會被調用一次。

此外還有2種類型的方法實例和靜態方法。兩種類型都可以接受參數。如果您使用靜態參數化方法,那麼您無法在該類的對象上調用該方法,因爲它們可以對該類的靜態變量進行操作。

實例參數化方法可以使用類的實例和靜態成員,並且可以在對象上調用它們。它們代表一種機制來對你調用該方法的對象執行某種操作。在這些方法中傳遞的參數(包括靜態和實例)可以作爲您想要完成的操作的輸入。 與構造函數在對象的instatantion時只被調用一次不同,您可以根據需要多次調用這些方法。

另一個經典的區別是構造函數總是返回對象的引用。這是默認的隱式行爲,我們不需要在簽名中明確指定。 然而,方法可以根據您的選擇返回任何東西。

實施例:

public class A { 

    String mA; 

    /* Constructor initilaizes the instance members */ 
    public A (String mA) { 
     this.mA = mA; 
    } 

    /* this is parameterized method that takes mB as input 
     and helps you operate on the object that has the instance 
     member mA */ 

    public String doOperation (String mB) { 
     return mA + " " + mB; 
    } 

    public static void main(String args[]) { 

      /* this would call the constructor and initialize the instance variable with "Hello" */ 
     A a = new A("Hello"); 

     /* you can call the methods as many times as   you want */ 
     String b= a.doOperation ("World"); 
     String c = a.doOperation ("How are you"); 

    } 
} 
0

他們有一個主要的區別是返回類型。一個構造函數不會返回任何東西,甚至無效。構造函數在類實例化時運行。另一方面,parameterized methods用於類型安全,即允許不需要投射的不同類。

public class Person { 

     String name ; 
     int id; 

//Default constructor 
     Person(){ 

     } 

//Parameterized constructor 
     Person(String name, int id){ 
      this.name = name; 
      this.id = id; 

     } 

     public static void main(String[] args) { 
      Person person = new Person("Jon Snow",1000); // class instantiation which set the instance variables name and id via the parameterised constructor 

      System.out.println(person.name); //Jon Snow 
      System.out.println(person.id); //1000 

      Person person1 = new Person(); //Calls the default constructor and instance variables are not set 

      System.out.println(person1.name); //null 
      System.out.println(person1.id); //0 
     } 

    } 
0

方法&構造是完全不同的概念&供應不同的目的。

構造函數指定用於在創建對象時初始化對象和任何設置/數據集。您不能再次調用構造函數&。它將被每個對象調用一次(您可以從該類的另一個構造函數調用一個構造函數)

方法是一個功能單元,您可以根據需要調用/重用它們。

希望這對我很有幫助 謝謝,

+0

請提供一個示例代碼片段作爲OP。 OP對此有所瞭解可能有所幫助。 –

+0

非常感謝, – administr4tor

相關問題