java抽象类泛型,Java方法派生如何与泛型和抽象类一起工作?

I ran into a situation today where Java was not invoking the method I expected -- Here is the minimal test case: (I'm sorry this seems contrived -- the 'real world' scenario is substantially more complex, and makes much more sense from a "why the hell would you do that?" standpoint.)

I'm specifically interested in why this happens, I don't care about redesign suggestions. I have a feeling this is in Java Puzzlers, but I don't have my copy handy.

See the specific question in commends within Test.getValue() below:

public class Ol2 {

public static void main(String[] args) {

Test t = new Test() {

protected Integer value() { return 5; }

};

System.out.println(t.getValue());

}

}

abstract class Test {

protected abstract T value();

public String getValue() {

// Why does this always invoke makeString(Object)?

// The type of value() is available at compile-time.

return Util.makeString(value());

}

}

class Util {

public static String makeString(Integer i){

return "int: "+i;

}

public static String makeString(Object o){

return "obj: "+o;

}

}

The output from this code is:

obj: 5

解决方案

No, the type of value is not available at compile time. Keep in mind that javac will only compile one copy of the code to be used for all possible T's. Given that, the only possible type for the compiler to use in your getValue() method is Object.

C++ is different, because it will eventually create multiple compiled versions of the code as needed.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值