How does Java method dispatch work with Generics and abstract classes?

徘徊边缘 提交于 2019-12-01 16:42:37

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.

Because the decision about what makeString() to use is made at compile-time and, based on the fact that T could be anything, must be the Object version. Think about it. If you did Test<String> it would have to call the Object version. As such all instances of Test<T> will use makeString(Object).

Now if you did something like:

public abstract class Test<T extends Integer> {
  ...
}

things might be different.

Josh Bloch's Effective Java has an excellent discussion clarifying the confusion that arises because dispatch works differently for overloaded vs overridden (in a subclass) methods. Selection among overloaded methods---the subject of this question---is determined at compile time; selection among overridden methods is done at run time (and therefore gets knowledge of the specific type of the object.)

The book is much clearer than my comment: See "Item 41: Use overloading judiciously"

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!