You are on page 1of 2

1/17/2016

Generics,Inheritance,andSubtypes(TheJavaTutorials>LearningtheJavaLanguage>Generics(Updated))

Documentation

TheJavaTutorials
Trail:LearningtheJavaLanguage
Lesson:Generics(Updated)

Generics,Inheritance,andSubtypes
Asyoualreadyknow,itispossibletoassignanobjectofonetypetoanobjectofanothertypeprovidedthatthetypesarecompatible.Forexample,
youcanassignan Integertoan Object,since Objectisoneof Integer'ssupertypes:
ObjectsomeObject=newObject();
IntegersomeInteger=newInteger(10);
someObject=someInteger;//OK

Inobjectorientedterminology,thisiscalledan"isa"relationship.Sincean Integerisakindof Object,theassignmentisallowed.But Integerisalsoa


kindof Number,sothefollowingcodeisvalidaswell:
publicvoidsomeMethod(Numbern){/*...*/}
someMethod(newInteger(10));//OK
someMethod(newDouble(10.1));//OK

Thesameisalsotruewithgenerics.Youcanperformagenerictypeinvocation,passing Numberasitstypeargument,andanysubsequentinvocation
of addwillbeallowediftheargumentiscompatiblewith Number:
Box<Number>box=newBox<Number>();
box.add(newInteger(10));//OK
box.add(newDouble(10.1));//OK

Nowconsiderthefollowingmethod:
publicvoidboxTest(Box<Number>n){/*...*/}

Whattypeofargumentdoesitaccept?Bylookingatitssignature,youcanseethatitacceptsasingleargumentwhosetypeis Box<Number>.Butwhat
doesthatmean?Areyouallowedtopassin Box<Integer>or Box<Double>,asyoumightexpect?Theansweris"no",because Box<Integer>and
Box<Double>arenotsubtypesof Box<Number>.
Thisisacommonmisunderstandingwhenitcomestoprogrammingwithgenerics,butitisanimportantconcepttolearn.

Box<Integer>isnotasubtypeof Box<Number>eventhough Integerisasubtypeof Number.

Note:Giventwoconcretetypes Aand B(forexample, Numberand Integer), MyClass<A>hasnorelationshipto MyClass<B>,regardlessof


whetherornot Aand Barerelated.Thecommonparentof MyClass<A>and MyClass<B>is Object.
Forinformationonhowtocreateasubtypelikerelationshipbetweentwogenericclasseswhenthetypeparametersarerelated,see
WildcardsandSubtyping.

GenericClassesandSubtyping
Youcansubtypeagenericclassorinterfacebyextendingorimplementingit.Therelationshipbetweenthetypeparametersofoneclassorinterface
andthetypeparametersofanotheraredeterminedbythe extendsand implementsclauses.
Usingthe Collectionsclassesasanexample, ArrayList<E>implements List<E>,and List<E>extendsCollection<E>.So ArrayList<String>isasubtypeof
List<String>,whichisasubtypeof Collection<String>.Solongasyoudonotvarythetypeargument,thesubtypingrelationshipispreservedbetween

https://docs.oracle.com/javase/tutorial/java/generics/inheritance.html

1/2

1/17/2016

Generics,Inheritance,andSubtypes(TheJavaTutorials>LearningtheJavaLanguage>Generics(Updated))

thetypes.

Asample Collectionshierarchy
Nowimaginewewanttodefineourownlistinterface, PayloadList,thatassociatesanoptionalvalueofgenerictype Pwitheachelement.Its
declarationmightlooklike:
interfacePayloadList<E,P>extendsList<E>{
voidsetPayload(intindex,Pval);
...
}

Thefollowingparameterizationsof PayloadListaresubtypesof List<String>:


PayloadList<String,String>
PayloadList<String,Integer>
PayloadList<String,Exception>

Asample PayloadListhierarchy

Youruseofthispageandallthematerialonpagesunder"TheJavaTutorials"bannerissubjecttotheselegal
notices.
Copyright1995,2015Oracleand/oritsaffiliates.Allrightsreserved.

Problemswiththeexamples?TryCompilingandRunningtheExamples:
FAQs.
Complaints?Compliments?Suggestions?Giveusyourfeedback.

Previouspage:GenericMethodsandBoundedTypeParameters
Nextpage:TypeInference

https://docs.oracle.com/javase/tutorial/java/generics/inheritance.html

2/2

You might also like