簡體   English   中英

何時在Java中使用參數化方法與參數化構造函數

[英]When to use Parameterized Method vs Parameterized Constructor in Java

我剛剛開始學習Java,並從Java第9版Herber Schildt [第6章]中談到了參數化方法和參數化構造函數的主題,

我了解如何聲明它們以及它們如何工作,但是我對它們的用法, 何時使用參數化方法以及何時使用參數化構造函數感到困惑

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

它們的主要區別在於返回類型。 構造函數不返回任何內容,甚至不返回void。 實例化類時,將運行構造函數。 另一方面, 參數化方法用於類型安全,即允許不同的類而無需強制轉換。

 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
        }

    }

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

您可以將“構造函數”視為當您為類創建對象時就會調用的函數。 在一個類中,您可以有許多實例變量,即該類的每個對象都有其實例變量的副本。 因此,每當使用new ClassName (args)語句創建新對象時,都可以在構造函數中初始化該對象的實例變量的值,因為在實例化對象時將首先調用該對象。 記住,創建對象時,構造函數只會被調用一次。

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

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

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

例:

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");

     }
}

方法和構造函數是完全不同的概念並且服務於不同的目的。

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

方法是一個功能單元,您可以隨意調用/重用它們。

希望對您有所幫助謝謝,

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM