Tirmean
Tirmean

Reputation: 408

Generic Interface polymorphism casting error

Following, is a very simple example.
Why do I need to use casting at (String)classA.getOut();

Compiler should now that type is String.

Thanks

ITest classA = new CLASSA();
String str = classA.getOut(); //Casting error

class CLASSA implements ITest<String> {
    public String getOut() {
        return "X";
    }
}

interface ITest<T> {
    public T getOut();

}

Upvotes: 0

Views: 52

Answers (3)

bcsb1001
bcsb1001

Reputation: 2907

You have declared classA as a raw type. This means that the compiler doesn't know that it's getOut() method will return a String. Change your declaration to:

ITest<String> classA = new CLASSA();

Upvotes: 1

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62864

It's because you're using raw-types instead of generics.

When you do

ITest classA = new CLASSA();

the compile-time type is an raw ITest, which replaces the T with Object and so introduces a method with signaure

public Object getOut() 

This is why the compiler forces you to cast the Object to String (the compiler doesn't know that at Runtime the method would return an object that is compatible with String).


A proper way of getting rid of the warning and the casting error is using Generics instead of raw types:

ITest<String> classA = new CLASSA();

Upvotes: 1

Smutje
Smutje

Reputation: 18123

The "interface type" of the variable classA is ITest and neither ITest<String> nor CLASSA so all the compiler knows that it has a method getOut of a raw (undefined) type.

Upvotes: 0

Related Questions