[英]How do covariant parameter types work in java
Given that Date has a method called "after(Date)" and Timestamp has a method the overrides it called "after(Timestamp)", why is the after method in Date called in the following code? 鉴于Date有一个名为“after(Date)”的方法,而Timestamp有一个覆盖它的方法叫做“after(Timestamp)”,为什么在下面的代码中调用Date中的after方法?
The question as to the unexpected results was asked 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());
}
results 结果
one: 1266873627200
two: 1266873627000
1266873627200 not after 1266873627000
Overloads are considered at compile-time; 在编译时考虑过载; overrides are considered at execution time. 在执行时考虑覆盖。
Timestamp overloads after
, it doesn't override an existing method - so your oneDate.after(twoDate)
is only considering the methods in java.util.Date
; 时间戳重载 after
,它不会覆盖现有方法 - 所以你的oneDate.after(twoDate)
只考虑java.util.Date
的方法; furthermore even if you use one.after(twoDate)
it would still only use after(Date)
because the compile-time type of twoDate
is Date
rather than Timestamp
. 此外,即使你使用one.after(twoDate)
它仍然只使用after(Date)
因为twoDate
的编译时类型是Date
而不是Timestamp
。
If you call one.after(two)
then that will use Timestamp.after(Timestamp)
. 如果调用one.after(two)
,然后将使用Timestamp.after(Timestamp)
。
Date.after(Date)
only considers the milliseconds - but Timestamp
only passes an integral number of seconds to the constructor of Date
, so oneDate
and twoDate
have an equal millisecond value in Date
, even though you passed different values to the constructors. Date.after(Date)
仅考虑毫秒 - 但Timestamp
仅向Date
的构造函数传递整数秒,因此即使您向构造函数传递了不同的值, oneDate
和twoDate
在Date
也具有相等的毫秒值。
It's worth noting this bit in the docs for Timestamp
though: 值得注意的是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. 由于Timestamp类和上面提到的java.util.Date类之间存在差异,因此建议代码不要将Timestamp值一般视为java.util.Date的实例。 The inheritance relationship between Timestamp and java.util.Date really denotes implementation inheritance, and not type inheritance. Timestamp和java.util.Date之间的继承关系实际上表示实现继承,而不是类型继承。
Sounds like a pretty poor use of inheritance to me, to be honest - but then Java's got plenty of those :( 对我来说听起来像是一个非常糟糕的继承使用,说实话 - 然后Java有很多这些:(
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.