OnJava8-Examples/generics/EpicBattle.java

73 lines
1.9 KiB
Java
Raw Permalink Normal View History

2015-09-07 11:44:36 -06:00
// generics/EpicBattle.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.
2016-01-25 18:05:55 -08:00
// Bounds in Java generics
2015-06-15 17:47:35 -07:00
import java.util.*;
interface SuperPower {}
2016-01-25 18:05:55 -08:00
2015-06-15 17:47:35 -07:00
interface XRayVision extends SuperPower {
void seeThroughWalls();
}
2016-01-25 18:05:55 -08:00
2015-06-15 17:47:35 -07:00
interface SuperHearing extends SuperPower {
void hearSubtleNoises();
}
2016-01-25 18:05:55 -08:00
2015-06-15 17:47:35 -07:00
interface SuperSmell extends SuperPower {
void trackBySmell();
}
class SuperHero<POWER extends SuperPower> {
POWER power;
SuperHero(POWER power) { this.power = power; }
POWER getPower() { return power; }
}
class SuperSleuth<POWER extends XRayVision>
extends SuperHero<POWER> {
SuperSleuth(POWER power) { super(power); }
void see() { power.seeThroughWalls(); }
}
class
CanineHero<POWER extends SuperHearing & SuperSmell>
2015-06-15 17:47:35 -07:00
extends SuperHero<POWER> {
CanineHero(POWER power) { super(power); }
void hear() { power.hearSubtleNoises(); }
void smell() { power.trackBySmell(); }
}
class SuperHearSmell
implements SuperHearing, SuperSmell {
@Override public void hearSubtleNoises() {}
@Override public void trackBySmell() {}
2015-06-15 17:47:35 -07:00
}
2016-01-25 18:05:55 -08:00
class DogPerson extends CanineHero<SuperHearSmell> {
DogPerson() { super(new SuperHearSmell()); }
2015-06-15 17:47:35 -07:00
}
public class EpicBattle {
// Bounds in generic methods:
static <POWER extends SuperHearing>
void useSuperHearing(SuperHero<POWER> hero) {
hero.getPower().hearSubtleNoises();
}
static <POWER extends SuperHearing & SuperSmell>
void superFind(SuperHero<POWER> hero) {
hero.getPower().hearSubtleNoises();
hero.getPower().trackBySmell();
}
public static void main(String[] args) {
2016-01-25 18:05:55 -08:00
DogPerson dogPerson = new DogPerson();
useSuperHearing(dogPerson);
superFind(dogPerson);
2015-06-15 17:47:35 -07:00
// You can do this:
2016-01-25 18:05:55 -08:00
List<? extends SuperHearing> audioPeople;
2015-06-15 17:47:35 -07:00
// But you can't do this:
2016-01-25 18:05:55 -08:00
// List<? extends SuperHearing & SuperSmell> dogPs;
2015-06-15 17:47:35 -07:00
}
2015-09-07 11:44:36 -06:00
}