[英]Initialization of instance variables that have not been declared
我是Java新手,對此感到困惑:UserAccount是另一個類,我如何在此抽象類Person中初始化用戶
public abstract class Person {
private String name;
private String email;
public Person(String name, String email, UserAccount user) {
//initalize user
this.name = name;
this.email = email;
//user?
}
public class UserAccount {
private String username;
private String password;
public UserAccount(String username, String password) {
this.username = username;
this.password = password;
}
在您的代碼中,您執行了所謂的“控制反轉” ,盡管在這種情況下其應用可能不是最佳示例。 在Person
結構中接收到UserAccount
作為參數時,您實際上可能希望將其存儲為Person
類的字段/屬性:
public abstract class Person {
private String name;
private String email;
private User user; // Add field user
public Person(String name, String email, UserAccount user) {
this.name = name;
this.email = email;
this.user = user; // Inversion of Control: assume user is already constructed
}
}
簡而言之:在構建用戶之前,您需要先構建UserAccount
:
// first construct the account...
UserAccount user = new UserAccount("John", "123secret321");
// ... then pass this account to a person
Person person = new Person("John", "john@doe.com", user);
但是,可以讓Person
的構造函數完全處理UserAccount
的構造,如下所示:
// signature has changed, pass all necessary information to Person, let it construct a UserAccount for us.
public Person(String name, String email, String userName, String password) {
this.name = name;
this.email = email;
this.user = new UserAccount(userName, password); // construct the user with the given information
}
雖然您不能分別調用Person
的構造函數(由於該類是abstract
),但是在構造子類時(例如,構造函數被調用)
public class FinishedPerson extends Person {
private Date birthDate;
public FinishedPerson(String name, String email, Date birthDate, String username, String password) {
// call Person's constructor that, amongst other things, initializes the field user.
super(name, email, username, password);
this.birthDate = birthDate;
}
}
我希望這有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.