OnJava8-Examples/generics/BasicBounds.java

62 lines
1.6 KiB
Java
Raw Normal View History

2015-04-20 15:36:01 -07:00
//: generics/BasicBounds.java
2015-05-29 14:18:51 -07:00
// <20>2015 MindView LLC: see Copyright.txt
2015-04-20 15:36:01 -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> {
2015-05-18 23:05:20 -07:00
2015-04-20 15:36:01 -07:00
// 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; }
}
2015-05-18 23:05:20 -07:00
interface Weight { int weight(); }
2015-04-20 15:36:01 -07:00
// 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 {
2015-05-05 11:20:13 -07:00
@Override
2015-04-20 15:36:01 -07:00
public java.awt.Color getColor() { return null; }
2015-05-05 11:20:13 -07:00
@Override
2015-04-20 15:36:01 -07:00
public int weight() { return 0; }
2015-05-18 23:05:20 -07:00
}
2015-04-20 15:36:01 -07:00
public class BasicBounds {
public static void main(String[] args) {
2015-05-05 11:20:13 -07:00
Solid<Bounded> solid =
new Solid<>(new Bounded());
2015-04-20 15:36:01 -07:00
solid.color();
solid.getY();
solid.weight();
}
} ///:~