首页 > 解决方案 > 带参数的对象仍然显示参考变量的初始值

问题描述

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。你怎么看 ?这是我在这里的第一篇文章,如果这里的发帖形式不正确,很抱歉。谢谢!

标签: javadefault-valueinstance-variables

解决方案


你的构造函数应该是:

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

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

基本上,您需要分配要传递给实例变量的值。


推荐阅读