Professional Documents
Culture Documents
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
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.
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);
...
}
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