协变量参数类型如何在Java中工作 [英] How do covariant parameter types work in java

查看:77
本文介绍了协变量参数类型如何在Java中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于Date有一个名为"after(Date)"的方法,而Timestamp有一个名为"after(Timestamp)"的方法,为什么下面的Date中的 after 方法被调用代码?

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?

询问有关意外结果的问题这里.

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());
    }

结果

one: 1266873627200
two: 1266873627000
1266873627200 not after 1266873627000

推荐答案

在编译时考虑了重载.覆盖将在执行时考虑.

Overloads are considered at compile-time; overrides are considered at execution time.

时间戳重载 after,它不会覆盖现有的方法-因此,您的oneDate.after(twoDate)仅考虑java.util.Date中的方法;此外,即使您使用one.after(twoDate),它也会 still 仅使用after(Date),因为twoDate的编译时类型是Date而不是Timestamp.

Timestamp overloads after, it doesn't override an existing method - so your oneDate.after(twoDate) is only considering the methods in 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(two),则那个将使用Timestamp.after(Timestamp).

If you call one.after(two) then that will use Timestamp.after(Timestamp).

Date.after(Date)仅考虑毫秒-但Timestamp仅将整数秒传递给Date的构造函数,因此即使oneDatetwoDateDate中具有相等的毫秒值,即使您将不同的值传递给了构造函数.

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.

文档中的这一点值得注意对于Timestamp :

由于两者之间的差异 时间戳记类和java.util.Date 上面提到的课,是 建议不要查看代码 时间戳记值通常作为 java.util.Date的实例.这 之间的继承关系 时间戳和java.util.Date确实 表示实现继承, 而不是继承.

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有了很多这些:(

Sounds like a pretty poor use of inheritance to me, to be honest - but then Java's got plenty of those :(

这篇关于协变量参数类型如何在Java中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆