您現在的位置是:首頁 > 武術

java構造方法的過載

  • 由 虛雲幻仙 發表于 武術
  • 2023-01-15
簡介}*不能再定義User(int id,String pwd) 形參的名字不指代類的屬性pwd和name型別相同名字不同,在構造方法執行時無法區分輸入的String型是name屬性還是pwd屬性*public User(int id, S

如何實現方法的過載

/**

* 測試構造方法的過載

*/

public class User {

int id;

String name;

String pwd;

public User(int id){

this。id = id;

//用this。標明物件的id 和形參id區分

}

public User(){}

//透過形參列表的不同來構成構造方法的過載

public User(int id,String name){

this。id = id;

this。name = name;

}

/*不能再定義User(int id,String pwd) 形參的名字不指代類的屬性

pwd和name型別相同名字不同,在構造方法執行時無法區分輸入的String型是name屬性還是pwd屬性

*/

public User(int id, String name, String pwd) {

this。id = id;

this。name = name;

this。pwd = pwd;

}

public static void main(String[] args) {

User u1 = new User();

User u2 = new User(001);

User u3 = new User(002,“n1”);

User u4 = new User(003,“n2”,“111111”);

}

}

java構造方法的過載

Top