首页 > 解决方案 > 如何将日期信息传递给 dateHired 的 MyDate 类?

问题描述

我试图让 Employee 类发送,day到MyDate 类。MyDate 类接收 3 个变量并生成一个 toString() 方法供 Employee 类使用。到目前为止我的代码:monthyear

员工类

package lab3;

public class Employee extends Person {

    String office;
    double salary;
    int day;
    int month;
    int year;
    MyDate dateHired;
    
    public Employee(String name) {
        super(name);
        this.office = "No office";
        this.salary = 1200.00;
        this.day = 1;
        this.month = 1;
        this.year = 1970;
    }
    
    public Employee(String name, String address, String phoneNumber, String email, String office, double salary, int day, int month, int year) {
        super(name, address, phoneNumber, email);
        this.office = office;
        this.salary = salary;
        this.day = day;
        this.month = month;
        this.year = year;
    }
    
    public String getOffice() {
        return office;
    }
    
    public void setOffice(String office) {
        this.office = office;
    }
    
    public double getSalary() {
        return salary;
    }
    
    public void setSalary(double salary) {
        this.salary = salary;
    }
    
    public String toString() {
        return super.toString() + "\n" + "Office: " + getOffice()
        + "\n" + "Salary: " + getSalary() + "\n" + "Date Hired: " + dateHired.toString();
    }
}

MyDate 类

package lab3;

public class MyDate {

    public int day, month, year;

    public MyDate() {
        day = 1;
        month = 1;
        year = 1970;
    }
    
    public MyDate(int day, int month, int year) {
        this.day = day;
        this.month = month;
        this.year = year;
    }
    
    public int getDay() {
        return day;
    }   
    public void setDay(int day) {
        this.day = day;
    }
    public int getMonth() {
        return month;
    }
    public void setMonth(int month) {
        this.month = month;
    }
    public int getYear() {
        return year;
    }   
    public void setYear(int year) {
        this.year = year;
    }       
    public String toString() {
        return getDay() + "/" + getMonth() + "/" + getYear();
    }
}

标签: java

解决方案


由于您MyDate在类中有一个属性,因此Employee您不需要day/month/year,而是MyDateEmployee构造函数中实例化 a

public Employee(String name) {
    super(name);
    this.office = "No office";
    this.salary = 1200.00;
    this.dateHired = new MyDate();              // uses the MyDate default constructor
    // this.dateHired = new MyDate(1, 1, 1970); // does same with the other constructor
}

public Employee(String name, String address, String phoneNumber, String email,
                String office, double salary, int day, int month, int year) {
    super(name, address, phoneNumber, email);
    this.office = office;
    this.salary = salary;
    this.dateHired = new MyDate(day, month, year);
}

推荐阅读