2015-09-07 11:44:36 -06:00
|
|
|
|
// generics/BasicBounds.java
|
2015-11-14 16:18:05 -08:00
|
|
|
|
// <20>2016 MindView LLC: see Copyright.txt
|
2015-06-15 17:47:35 -07:00
|
|
|
|
|
|
|
|
|
interface HasColor { java.awt.Color getColor(); }
|
|
|
|
|
|
|
|
|
|
class Colored<T extends HasColor> {
|
|
|
|
|
T item;
|
|
|
|
|
Colored(T item) { this.item = item; }
|
|
|
|
|
T getItem() { return item; }
|
|
|
|
|
// The bound allows you to call a method:
|
|
|
|
|
java.awt.Color color() { return item.getColor(); }
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
class Dimension { public int x, y, z; }
|
|
|
|
|
|
|
|
|
|
// This won't work -- class must be first, then interfaces:
|
|
|
|
|
// class ColoredDimension<T extends HasColor & Dimension> {
|
|
|
|
|
|
|
|
|
|
// Multiple bounds:
|
|
|
|
|
class ColoredDimension<T extends Dimension & HasColor> {
|
|
|
|
|
T item;
|
|
|
|
|
ColoredDimension(T item) { this.item = item; }
|
|
|
|
|
T getItem() { return item; }
|
|
|
|
|
java.awt.Color color() { return item.getColor(); }
|
|
|
|
|
int getX() { return item.x; }
|
|
|
|
|
int getY() { return item.y; }
|
|
|
|
|
int getZ() { return item.z; }
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
interface Weight { int weight(); }
|
|
|
|
|
|
|
|
|
|
// As with inheritance, you can have only one
|
|
|
|
|
// concrete class but multiple interfaces:
|
|
|
|
|
class Solid<T extends Dimension & HasColor & Weight> {
|
|
|
|
|
T item;
|
|
|
|
|
Solid(T item) { this.item = item; }
|
|
|
|
|
T getItem() { return item; }
|
|
|
|
|
java.awt.Color color() { return item.getColor(); }
|
|
|
|
|
int getX() { return item.x; }
|
|
|
|
|
int getY() { return item.y; }
|
|
|
|
|
int getZ() { return item.z; }
|
|
|
|
|
int weight() { return item.weight(); }
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
class Bounded
|
|
|
|
|
extends Dimension implements HasColor, Weight {
|
|
|
|
|
@Override
|
|
|
|
|
public java.awt.Color getColor() { return null; }
|
|
|
|
|
@Override
|
|
|
|
|
public int weight() { return 0; }
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public class BasicBounds {
|
|
|
|
|
public static void main(String[] args) {
|
|
|
|
|
Solid<Bounded> solid =
|
|
|
|
|
new Solid<>(new Bounded());
|
|
|
|
|
solid.color();
|
|
|
|
|
solid.getY();
|
|
|
|
|
solid.weight();
|
|
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
|
}
|
|
|
|
|
/* Output: (None) */
|