(13) Java Generics

(13) Java Generics - Generic programming CMSC 132:...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
CMSC 132: Object-Oriented Programming II Generic Programming 1 Department of Computer Science University of Maryland, College Park Generic programming Generic programming refers to defining constructs that can be used with different data types, for example having code that operates upon different types 2 Generic programming is implemented in Java through 1. Inheritance A extends B 2. Type variables <A> Generic programming examples Inheritance Type variables class A { … } class B extends A { … } public class C { static void doWork(A a) { } class A { … } class B { … } class C<T> { void doWork(T x) { } 3 doWork() is applied to objects of both class A and B } A aVar= new A(); B bVar= new B(); doWork(aVar); doWork(bVar); } C<A> ca= new C<A>(); C<B> cb= new C<B>(); A a= new A(); B b= new B(); ca.doWork(a); cb.doWork(b); Generic classes A generic class is one that has one or more type variables Example: class ArrayList<E> To instantiate or create a reference to a generic class, provide an actual type for each of its 4 type variables Valid types are classes and interfaces Examples: ArrayList<String> ArrayList<Comparable> Primitive types can't be used, but their wrapper classes can Example: ArrayList<Integer>
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 11/16/2011 for the course CMSC 132 taught by Professor Padua-perez during the Fall '08 term at Maryland.

Page1 / 3

(13) Java Generics - Generic programming CMSC 132:...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online