简体   繁体   English

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

[英]Initialization of instance variables that have not been declared

I'm new to java and I'm confused by this: UserAccount is another class how do i initialize user in this abstract class Person 我是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;
}

In your code, you did what is known as Inversion of Control , although its application in this scenario may be not the best example. 在您的代码中,您执行了所谓的“控制反转” ,尽管在这种情况下其应用可能不是最佳示例。 When receiving a UserAccount as a parameter in the construct of Person , you may actually want to store it as a field/attribute of class Person : 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
    }
}

In short: you would construct the UserAccount before constructing the user like this: 简而言之:在构建用户之前,您需要先构建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);

There is, however, the possibility to let the constructor of Person fully handle the construction of a UserAccount like this: 但是,可以让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
    }

While you cannot call the constructor of Person dicretly (since the class is abstract ), the constructor gets called, when a sub-class is constructed, eg 虽然您不能分别调用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;
    }
}

I hope this helps. 我希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM