鉴于Date有一个名为“after(Date)”的方法,而Timestamp有一个方法覆盖它称为“after(Timestamp)”,为什么在下面的代码中调用Date中的after方法?
关于意外结果的问题被问到here.
java.sql.Timestamp one = new java.sql.Timestamp(1266873627200L); java.sql.Timestamp two = new java.sql.Timestamp(1266873627000L); java.util.Date oneDate = (java.util.Date) one; java.util.Date twoDate = (java.util.Date) two; System.out.println("one: " + oneDate.getTime()); System.out.println("two: " + twoDate.getTime()); if (oneDate.after(twoDate)) { System.out.println(oneDate.getTime() + " after " + twoDate.getTime()); } else { System.out.println(oneDate.getTime() + " not after " + twoDate.getTime()); }
结果
one: 1266873627200 two: 1266873627000 1266873627200 not after 1266873627000
解决方法
在编译时考虑过载;在执行时考虑覆盖.
时间戳重载之后,它不会覆盖现有方法 – 所以你的oneDate.after(twoDate)只考虑java.util.Date中的方法;此外,即使你使用one.after(twoDate),它仍然只会使用after(Date),因为twoDate的编译时类型是Date而不是Timestamp.
如果你调用one.after(two),那么将使用Timestamp.after(Timestamp).
Date.after(Date)仅考虑毫秒 – 但Timestamp仅向Date的构造函数传递整数秒,因此即使您向构造函数传递了不同的值,oneDate和twoDate在Date中也具有相等的毫秒值.
值得注意的是docs for Timestamp
中的这一点:
Due to the differences between the
Timestamp class and the java.util.Date
class mentioned above,it is
recommended that code not view
Timestamp values generically as an
instance of java.util.Date. The
inheritance relationship between
Timestamp and java.util.Date really
denotes implementation inheritance,
and not type inheritance.
对我来说听起来像是一个非常糟糕的继承使用,说实话 – 然后Java有很多这些:(