如何创建一个使用另一个类的变量的 java 对象?

如何创建一个使用另一个类的变量或调用整个构造函数的 java 对象?


比如accountNumber, firstName, lastName, phone都是传入address的变量,由street, city, state, zip组成,已经创建好了:


Address address = new Address(street, city, state, zip);

数据仅由兆字节组成,并且已经创建:


Data data = new Data(megabytes);

这就是我对客户对象的看法:


Customer customer = new Customer(accountNumber, firstName, lastName, address, phone, data);

这应该是一个“重载的构造函数”,但我不明白那是什么意思。


这是我到目前为止的构造函数:


public Customer(String accountNumber, String firstName, String lastName, Address address, int phone, Data megabytes)

{

    this.accountNumber = accountNumber;

    this.firstName = firstName; 

    this.lastName = lastName;

    this.address = address; 

    this.phone = phone; 

    this.megabytes= megabytes; 

}

我收到错误:


The constructor Customer(String, String, String, Address, int, Data) is undefined


守候你守候我
浏览 91回答 1
1回答

12345678_0001

乍一看,一切似乎都很好。我希望你在编译之前保存了文件。既然你提到你不明白什么是重载构造函数,我会尽力解释一下。重载的构造函数具有相同的构造函数名称,但它在以下方面与其他构造函数不同 -它有不同数量的正式参数构造函数形参类型顺序不同这是一个例子 -public class Customer {    private String firstName;    private String lastName;    private int phoneNumber;    public Customer() {        // default constructor    }    public Customer(String firstName) {        this.firstName = firstName;    }    public Customer(String firstName, String lastName) {        this.firstName = firstName;        this.lastName = lastName;    }    public Customer(String firstName, String lastName, int phoneNumber) {        this.firstName = firstName;        this.lastName = lastName;        this.phoneNumber = phoneNumber;    }    public Customer(int phoneNumber, String firstName, String lastName) {        this.phoneNumber = phoneNumber;          this.firstName = firstName;        this.lastName = lastName;    }// This is not an overloaded constructor as there is already a constructor of type// Customer(String, String)//    public Customer(String lastName, String firstName) {//        this.lastName = lastName;//        this.firstName = firstName;//    }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java