public class Test
{
public static void main(String [] args)
{
int i;
Date[] days;
days = new Date[3];
for (i=0; i<3; i++)
{
days[i] = new Date(2015, 9, i+2);
}
}
}
class Date
{
int year, month, day;
public Date(int y, int m, int d)
{
year = y;
month = m;
day = d;
}
}
而且我在第11行添加System.out.println(day[i]);打印出来的是
Date@de6ced
Date@c17164
Date@1fb8ee3
应该是这三个数组在栈中引用的地址。
可以在main里这样打印
System.out.println(day[i].year + " " + day[i].month + " " + day[i].day);
其实按照面向对象的思想day,month,year应该声明为private,然后在Data类里面写打印函数,再在外面调用这个打印函数。
重写toString方法
class Date
{
int year, month, day;
public Date(int y, int m, int d)
{
year = y;
month = m;
day = d;
}
public String toString(){//重写这个方法
return year+"-"+month+"-"+day;
}
}
重写toString.因为System.out.println(a)等价于System.out.println(a.toString()),toString是可以重写的,因你是你自己定义的类,需要重写,你现在打印的是每个对象的哈希码(不是地址),因此重写toString
有时期和字符串相互转化的函数,你先把日期类型的变量转换成字符串型的,然后再输出就好了,我给你举个
public class Test1{
public static void main(String[] args) {
Date date = null;
try {
date = new SimpleDateFormat("yyyy/mm/dd hh:mm:ss").parse("2015/9/1 0:00:00");
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(date);
}
}