Unbounded
parameter type
- An
unbounded
generic type parameter
T
is specified as
follows:
<T> ( ≡ <T extends Object> )
|
Meaning:
- You can use
any
object (reference) type
to make the
parameter type
T into a
specific type
|
- When an
unbounded
generic type parameter
T is used
in a generic class
definition:
- The type parameter <T> is
replaced by:
Object
|
-
However,
sometimes
the class
Object is
inappropriate
as the parent class
Example:
- Object does
not has
certain
required method(s)
used in the code
|
|
Bounded
parameter type
- An
bounded
generic type parameter
T
is specified as
follows:
Meaning:
- You can
only use a
sub-type (is-a) of
SuperClass
to make
T into a
specific type
|
- When a
bounded
generic type parameter
T is used
in a generic class
definition:
- The type parameter <T> is
replaced by the
bounding type !
(Instead of Object)
|
- The use of
bounded
type parameter is
necessary when
you have used a
method in your
code that is
not defined in the
Object class
- We will see an example
next
|
|
Example of defining a
method with a
bounded generic type
- Consider the
method
smallerArea( ) that
compares the
area of
2 Circle objects:
public static boolean smallerArea( Circle o1, Circle o2 )
{
return o1.getArea() < o2.getArea();
}
|
- We will need
another
method
to
compares the
area of
2 Rectangle objects:
public static boolean smallerArea( Rectangle o1, Rectangle o2 )
{
return o1.getArea() < o2.getArea();
}
|
- We will need
another
2 method
to
compares the
area of
Circle objects
and Rectangle objects:
public static boolean smallerArea( Circle o1, Rectangle o2 ) ...
public static boolean smallerArea( Rectangle o1, Circle o2 ) ...
|
|
DEMO:
demo/06-generics/04-bounded/Demo.java
(comment a method out and recompile !)
Example of defining a
method with a
bounded generic type
DEMO:
demo/06-generics/04-bounded/Demo2.java
Example of defining a
method with a
bounded generic type
-
Solution:
we limit
the type parameter with
a bounded
generic parameter of
the class GeometricObject:
public static <T extends GeometricObject> boolean smallerArea( T o1, T o2 )
{
return o1.getArea() < o2.getArea();
}
|
- This method will
only
accept
arguments that are
subclasses of
GeometricObject
(that has the getArea()
method):
Example:
Circle c1 = new Circle("red", 1);
Rectangle r1 = new Rectangle("red", 1, 1);
System.out.println( smallerArea( c1, c1 ) );
System.out.println( smallerArea( r1, r1 ) );
System.out.println( smallerArea( c1, r1 ) );
|
|
DEMO:
demo/06-generics/04-bounded/Demo4.java
Looking under the hood of the Java compiler
Postscript
- There is a lot more
material on
generic class in
the text book
- These topic is outside the
scope of
this course.
- If interested in this topic,
please study the remaining sections
(19.5 - 19.10)
on your own
and ask me if you have questions during my office hours.
|
❮
❯