【问题标题】:Object with arguments still displays initial values of reference variables带参数的对象仍然显示参考变量的初始值
【发布时间】:2019-03-15 06:31:32
【问题描述】:
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。你怎么看 ?这是我在这里的第一篇文章,如果这里的发帖形式不正确,很抱歉。 谢谢!

【问题讨论】:

  • 提示:查看构造函数的主体。你在用参数做什么?您希望这些字段如何获取值?
  • 术语点:methodsconstructors有论据;对象没有。

标签: java default-value instance-variables


【解决方案1】:

你的构造函数应该是:

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

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

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

【讨论】:

    【解决方案2】:

    你的构造函数没有对你的字段做任何事情

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

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

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

    【讨论】:

      【解决方案3】:

      在构造函数中,您正在讨论“theDay”、“theMonth”、“theYear”。将它们设置为 'day','month','year' 类变量。

      day=theDay
      month=theMonth
      year=theYear
      

      内部构造函数

      【讨论】:

      • 你不同意,如果你想发布一个答案,它应该(至少)是可编译的?
      猜你喜欢
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 2013-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多