Wednesday, March 7, 2007

Lecture 21

Generic programming
public class x
{
private String s;
public x(String s){this.s = s;}
public String getS(){return s;}
}
if we need many classes with the same function but different instance field type.
we can
1. declare them all individually
2. use a generic class(better)

a generic is a class that takes a type as a parameter

public class x <T>
{
private T s;
public x(T s){this.s=s;}
public T getS(){return s;}
}

x<String&lgt; myX = new x<String&lgt;("hello");

Note:
-constructor declared in the class as
public x(......)

but called as x<String&lgt;(....)
-The type associated with the generic can be any reference type
(i.e. any object type)

e.g. String, GregorianCalendar, JFrame and so on.

-Cannot use primitives
e.g. x<int&lgt; myX = new x<int&lgt;(36) is illegal

-There exist "wrapper" subjects for every primitive type.
int -&lgt; Integer
char -&lgt; Character
double -&lgt; Double
and so on...

x<Integer&lgt; myX = new x<Integer&lgt;(36); is legal

more illegal uses of the type parameter "T"

T myT = new T(); not okay
T[] myTArray = new T[10]; not okay

cannot create an array of generics.
x<String&lgt;[] myXarray = new x <String&lgt;[10] is illegal

can a generic take more than one type ?
the answer is yes.

public class TwoTypeGeneric <FirstType, SecondType&lgt;
{
codes here
}

restricting Types
you may wish to constrain the type parameter as follows
1.the child of a given class
2. implements a give interface
why?
can use methods associated with the ancestor/interface
usage: the extends keyword is used for both interfaces and ancestors.

Require that T implements myInterface

public class x<T extends myInterface&lgt;

require that T is a descendant of ancestor
public class x<T extends ancestor&lgt;

Also legal to require more than one
at most one is a class and the rest can be interface
_ use ampersands (&) to be seperator
T -&amp;lgt; descendant of class B
implement interface C,D
public class x<T extends B&C&D&lgt;

No comments: