java - When is there need for Some<E extends Some<E>> instead of Some<E extends Some>? -
note: this question not enum-related, it's not duplicate. enum's forced compare only-with-itself because compiler generation of type parameter, not because java recursive type parameter.
i'm trying find advantage declaring class as:
public class some<e extends some<e>>
versus declaring as:
public class some<e extends some>
i have tried providing methods returning e
, methods returning some<e>
, different cross-calls in complicated class hierarchy , every time i've tried remove additional <e>
- no new errors/warnings came up.
can show me method proves advantage of additional <e>
? assume there exists 1 because of jdk declarations:<e extends comparable<? super e>>
responses other questions on gives example:
with additional construct, know class extends enum comparable against itself
but, can break theory:
public static class animal<e extends animal<e>> { public boolean compare(e other) {...} } public class cat extends animal<cat> { } public class dog extends animal<cat> { } // note "cat" !!!
despite generic recursion, i can still compare dog cat:
dog dog = new dog(); dog.compare(new cat());
transalting theory:
you know class extends animal comparable against itself
this false - comapred class dog extends animal cat, not itself.
there few situations in bound class some<e extends some<e>>
necessary. of time people write this, bound not utilized in code, , class some<e>
work well.
however, there particular situations in bound in class some<e extends some<e>>
used. example:
abstract class some<e extends some<e>> { abstract e foo(); some<e> bar() { return foo(); } }
as question -- class some<e extends some>
? well, first glaring issue you're using raw type. raw types should never used in new code. not convinced.
the raw type above class (class some<e extends some>
) does compile warning (which can ignore own peril). however, raw type means it's possible unsafe things it.
it takes effort come example demonstrate it's unsafe. here one:
abstract class some<e extends some> { abstract e foo(); some<e> bar() { return foo(); } } class somefoo extends some<somefoo> { somefoo foo() { return this; } } class somebar extends some<somefoo> { somefoo foo() { return new somefoo(); } } class somebaz extends some<somebar> { somebar foo() { return new somebar(); } } // in method: some<somebar> = new somebaz(); some<somebar> b = a.bar(); somebar c = b.foo();
the code compiles warnings no errors, , throws classcastexception
@ runtime.
Comments
Post a Comment