Created
October 18, 2011 19:14
-
-
Save zcox/1296389 to your computer and use it in GitHub Desktop.
Java forgetting parameterized return type
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Base<T extends Base> { | |
public T f1() { | |
return (T) this; //Warning => Type safety: Unchecked cast from Forgetful.Base<T> to T | |
} | |
public T f2() { | |
return (T) this; //Warning => Type safety: Unchecked cast from Forgetful.Base<T> to T | |
} | |
} | |
public class Sub<T extends Sub> extends Base<Sub> { | |
public T f3() { | |
return (T) this; | |
} | |
} | |
public class Test { | |
public static void main(String[] args) { | |
Base b0 = new Base().f1().f2(); | |
//Warning => Forgetful.Base is a raw type. References to generic type Forgetful.Base<T> should be parameterized | |
//Error => Type mismatch: cannot convert from Object to Forgetful.Base<Forgetful.Base> | |
//f1() is returning T (which is essentially Object) instead of Base | |
Base<Base> b = new Base<Base>().f1().f2(); | |
//no errors, but multiple warnings on each line... | |
Base<Base> b1 = new Base<Base>(); | |
Base<Base> b2 = b1.f1(); | |
Base<Base> b3 = b2.f2(); | |
//Error: The method f3() is undefined for the type Base | |
Sub<Sub> s = new Sub<Sub>().f1().f2().f3(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment