我是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;
}
最佳答案
在您的代码中,您执行了所谓的 Inversion of Control 操作,尽管它在这个场景中的应用可能不是最好的例子。当收到UserAccount
时作为 Person
构造中的参数,您实际上可能想将其存储为类 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
的 build 像这样:
// 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;
}
}
我希望这会有所帮助。
关于java - 未声明的实例变量的初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37330029/