初始化尚未声明的实例变量

时间:2016-05-19 17:18:23

标签: java oop variables constructor instance

我是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;
}

1 个答案:

答案 0 :(得分:1)

在您的代码中,您执行了所谓的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的构造:

    // 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;
    }
}

我希望这会有所帮助。