class Date {
private int year;
private String month;
private int day;
public Date() {
month = "January";
year = 1999;
day = 1;
} //End of Constructor 1
public Date(int year, String month, int day) {
setDate(year, month, day);
} //End of Constructor 2
public Date(int year) {
setDate(year, "January", 1);
} //End of Constructor 3
public void setDate(int year, String month, int day) {
this.year = year;
this.month = month;
this.day = day;
} //End of Constructor 4
}
public class Calendar {
public static void main(String[] args){
Date date1 = new Date(2009, "March", 3);
Date date2 = new Date(2010);
Date date3 = new Date();
}
}
在上面的代码中,date1、date2 和 date3 调用了哪些构造函数?调用构造函数后如何打印 date1、date2 和 date3 的结果?
我尝试了System.out.println(date1)
等,但它给了我奇怪的字符串,例如u.Date@15db9742
。
我期待看到 2009 年 3 月 1 日或类似的事情。
最佳答案
当您尝试打印对象时,会调用其 toString()
方法,该方法由所有对象继承
来自Object class
的java类(默认情况下是所有java类的父类(super class))。所以你必须重写类中的 toString() 方法
如果您需要打印对象的某些特定内容。默认情况下,此方法打印
类及其哈希码
。由于您尚未重写 toString()
,因此打印的字符串
包含对象类及其哈希码(u.Date@15....)。
您的构造函数调用由传递给构造函数的参数决定。
与 date1
一样,您按顺序传递了 3 个 int、string 和 int
类型的参数。
这与您的构造函数 2 个参数相匹配,即 int、string 和 int
。
因此,在 date1 对象构造中,将调用构造函数 2。
类似地,对于 date2,构造函数 3 被调用
对于 date3,调用默认构造函数,即 consturcot 1。
您标记的“构造函数4”不是构造函数,它只是一个方法。 构造函数没有返回类型。
再次,要按照您在问题中的预期进行打印,请重写类中的 toString()
方法,并在该方法中相应地格式化结果以获得预期结果。
关于Java初学者对构造函数的使用感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38417773/