Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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<T>.getValue() below:

public class Ol2 {  

    public static void main(String[] args) {  
        Test<Integer> t = new Test<Integer>() {  
            protected Integer value() { return 5; }  
        };  

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


abstract class Test<T> {  
    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
like image 974
rcreswick Avatar asked Jan 17 '09 01:01

rcreswick


People also ask

Can generics be applied at a method level?

Generics do not apply to void return type, they apply to the method as a whole. The name and restrictions on the generic parameter need to go somewhere in the text of your program. In a class declaration they follow the class name in angular brackets.

How does the compiler translate Java generics?

Generics in Java are implemented using a type erasure mechanism. The compiler translates all type parameters in the source code to their bounding type in the class file. A type parameter's bounding type is Object if a bound type is not specified.

How does generics work in Java?

Java Generic methods and generic classes enable programmers to specify, with a single method declaration, a set of related methods, or with a single class declaration, a set of related types, respectively. Generics also provide compile-time type safety that allows programmers to catch invalid types at compile time.

What is abstract class in Java PDF?

Abstraction lets you focus on what the object does instead of how it does it. A class which is declared as abstract is known as an abstract class. It can have abstract and non- abstract methods. It needs to be extended and its method implemented.


3 Answers

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.

like image 189
Darron Avatar answered Oct 12 '22 02:10

Darron


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.

like image 38
cletus Avatar answered Oct 12 '22 02:10

cletus


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"

like image 30
Joshua Goldberg Avatar answered Oct 12 '22 02:10

Joshua Goldberg