How do I inherit from a generic class in java? -
i have class following
public class foo<idtype extends writablecomparable<idtype>, edata extends writable> { public foo(); public foo(idtype foo; idtype bar){ this.foo = foo; this.bar = bar; } private idtype foo; private idtype bar; }
now 1 of usage of class following:
elist = new arraylist<foo<stringtype, emptytype>>();
so works fine:
now want extend class add 1 more field
private string foobar;
now, instance of have 3 fields.
two of them
foobar.foo //base class foobar.bar //base class foobar.foobar // new variable added
now, usage still same:
elist = new arraylist<foobar<stringtype, emptytype>>();
i tried simple extension:
public class foobar extends foo{ private string foobar; public foobar(string foobar){this.foobar = foobar;}
}
but when use
i error:
elist = new arraylist<foobar<stringtype, emptytype>>(); arraylist<foobar><stringtype,emptytype>> cannot resolved type
if want let user specify types subclass, specify same type parameters, , pass them on base:
public class foobar <idtype extends writablecomparable<idtype>, edata extends writable> extends foo<idtype, edata> { ... }
if want let user specify 1 of types, can that, e.g. want force integer
idtype
:
public class foobar <edata extends writable> extends foo<integer, edata> { ... }
if want use specific types base, same idea:
public class foobar extends foo<integer, something> { ... }
you can add type:
public class foobar <idtype extends writablecomparable<idtype>, edata extends writable, anothertype> extends foo<idtype, edata> { private anothertype x; ... }
the point is, specify own parameter types in subclass in way see fit, , can pass types base long compatible types.
edit: responding comment on question above, have specify constraints on foobar
type parameters match constraints on base foo
. example, following not sufficient:
public class foobar <idtype, edata> extends foo<idtype, edata> // <-- fail compile { ... }
this lead following compilation errors:
type parameter idtype not within bound type parameter edata not within bound
this because foo
expects types extend writablecomparable<idtype>
, writable
, respectively, above erroneous declaration of foobar
attempts pass types not meet constraints type parameters foo
.
your error, way, posted, not appear match code , has >
@ end. appears made typo when copying , pasting.
Comments
Post a Comment