OnJava8-Examples/generics/BasicBounds.java

63 lines
1.7 KiB
Java
Raw Normal View History

2015-09-07 11:44:36 -06:00
// generics/BasicBounds.java
// (c)2021 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
2016-09-23 13:23:35 -06:00
// Visit http://OnJava8.com for more book information.
2015-06-15 17:47:35 -07:00
interface HasColor { java.awt.Color getColor(); }
2016-01-25 18:05:55 -08:00
class WithColor<T extends HasColor> {
2015-06-15 17:47:35 -07:00
T item;
2016-01-25 18:05:55 -08:00
WithColor(T item) { this.item = item; }
2015-06-15 17:47:35 -07:00
T getItem() { return item; }
// The bound allows you to call a method:
java.awt.Color color() { return item.getColor(); }
}
2016-01-25 18:05:55 -08:00
class Coord { public int x, y, z; }
2015-06-15 17:47:35 -07:00
// This fails. Class must be first, then interfaces:
2016-01-25 18:05:55 -08:00
// class WithColorCoord<T extends HasColor & Coord> {
2015-06-15 17:47:35 -07:00
// Multiple bounds:
2016-01-25 18:05:55 -08:00
class WithColorCoord<T extends Coord & HasColor> {
2015-06-15 17:47:35 -07:00
T item;
2016-01-25 18:05:55 -08:00
WithColorCoord(T item) { this.item = item; }
2015-06-15 17:47:35 -07:00
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:
2016-01-25 18:05:55 -08:00
class Solid<T extends Coord & HasColor & Weight> {
2015-06-15 17:47:35 -07:00
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
2016-01-25 18:05:55 -08:00
extends Coord implements HasColor, Weight {
2015-06-15 17:47:35 -07:00
@Override
public java.awt.Color getColor() { return null; }
@Override public int weight() { return 0; }
2015-06-15 17:47:35 -07:00
}
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
}