带参数的对象仍然显示引用变量的初始值

Object with arguments still displays initial values of reference variables

public class Date {

    private int day;
    private int month;
    private int year;

    public Date(int theDay, int theMonth, int theYear) {
    }

    public void setDay(int theDay) {
        day = theDay;
    }

    public int getDay() {
        return day;
    }

    public void setMonth(int theMonth) {
        month = theMonth;
    }

    public int getMonth() {
        return month;
    }

    public void setYear(int theYear) {
        year = theYear;
    }

    public int getYear() {
        return year;
    }

    public void displayDate() {
        System.out.printf("The current date is: %d/%d/%d", getDay(), getMonth(), getYear() );
    }
}

+

public class DateTest {

    public static void main( String[] args ) {

        Date myDate = new Date(20, 5, 2010);

        myDate.displayDate();
    }
}

结果: 当前日期是: 0/0/0 预期结果:20/5/2010

我检查了很多次,我没有看到任何错误。确保记录更改并重新启动 Eclipse。你怎么看 ?这是我第一次在这里 post 顺便说一句,如果这里 posting 的形式不正确,我深表歉意。 谢谢!

在构造函数中,您正在争论 'theDay'、'theMonth'、'theYear'。将它们设置为等于 'day'、'month'、'year' class 变量。

day=theDay
month=theMonth
year=theYear

内部构造函数

您的构造函数应该是:

public Date(int theDay, int theMonth, int theYear) {

    this.day = theDay;
    this.month = theMonth;
    this.year = theYear;
}

基本上您需要将传递给实例变量的值赋值。

您的构造函数未对您的字段执行任何操作,因此

public Date(int theDay, int theMonth, int theYear) {
}

在创建对象时初始化文件:

 public Date(int theDay, int theMonth, int theYear) {
     day=theDay;
     month=theMonth;
     year=theYear;
 }