简体   繁体   中英

How do you create a java object that uses a variable from another class?

How do you create a java object that uses a variable from another class, or calls the entire constructor?

For example, accountNumber, firstName, lastName, phone are all variables passed in address is comprised of street, city, state, and zip, and has already been created:

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

Data is comprised of only megabytes, and has already been created:

Data data = new Data(megabytes);

This is what I have for the customer object:

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

This is supposed to be an "overloaded constructor", but I don't understand what that means.

This is the constructor I have so far:

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

I get the error:

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

At a glance everything seems fine. I hoped you saved the file before compiling.

Since you mentioned that you didn't understand what an overloaded constructor is, I'll try my best to explain that.

An overloaded constructor has the same constructor name but it differs from other constructors in the following ways -

  1. It has different number of formal arguments
  2. The order of type of formal parameters of the constructor are different

Here is an example -

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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