2015-09-07 11:44:36 -06:00
|
|
|
// generics/Mixins.java
|
2016-12-30 17:23:13 -08:00
|
|
|
// (c)2017 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
|
|
|
import java.util.*;
|
|
|
|
|
|
|
|
interface TimeStamped { long getStamp(); }
|
|
|
|
|
|
|
|
class TimeStampedImp implements TimeStamped {
|
|
|
|
private final long timeStamp;
|
|
|
|
public TimeStampedImp() {
|
|
|
|
timeStamp = new Date().getTime();
|
|
|
|
}
|
|
|
|
@Override
|
|
|
|
public long getStamp() { return timeStamp; }
|
|
|
|
}
|
|
|
|
|
|
|
|
interface SerialNumbered { long getSerialNumber(); }
|
|
|
|
|
|
|
|
class SerialNumberedImp implements SerialNumbered {
|
|
|
|
private static long counter = 1;
|
|
|
|
private final long serialNumber = counter++;
|
|
|
|
@Override
|
|
|
|
public long getSerialNumber() { return serialNumber; }
|
|
|
|
}
|
|
|
|
|
|
|
|
interface Basic {
|
|
|
|
void set(String val);
|
|
|
|
String get();
|
|
|
|
}
|
|
|
|
|
|
|
|
class BasicImp implements Basic {
|
|
|
|
private String value;
|
|
|
|
@Override
|
|
|
|
public void set(String val) { value = val; }
|
|
|
|
@Override
|
|
|
|
public String get() { return value; }
|
|
|
|
}
|
|
|
|
|
|
|
|
class Mixin extends BasicImp
|
|
|
|
implements TimeStamped, SerialNumbered {
|
|
|
|
private TimeStamped timeStamp = new TimeStampedImp();
|
|
|
|
private SerialNumbered serialNumber =
|
|
|
|
new SerialNumberedImp();
|
|
|
|
@Override
|
|
|
|
public long getStamp() { return timeStamp.getStamp(); }
|
|
|
|
@Override
|
|
|
|
public long getSerialNumber() {
|
|
|
|
return serialNumber.getSerialNumber();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public class Mixins {
|
|
|
|
public static void main(String[] args) {
|
|
|
|
Mixin mixin1 = new Mixin(), mixin2 = new Mixin();
|
|
|
|
mixin1.set("test string 1");
|
|
|
|
mixin2.set("test string 2");
|
|
|
|
System.out.println(mixin1.get() + " " +
|
2016-01-25 18:05:55 -08:00
|
|
|
mixin1.getStamp() + " " +
|
|
|
|
mixin1.getSerialNumber());
|
2015-06-15 17:47:35 -07:00
|
|
|
System.out.println(mixin2.get() + " " +
|
2016-01-25 18:05:55 -08:00
|
|
|
mixin2.getStamp() + " " +
|
|
|
|
mixin2.getSerialNumber());
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
}
|
|
|
|
/* Output:
|
2016-07-27 11:12:11 -06:00
|
|
|
test string 1 1469638250315 1
|
|
|
|
test string 2 1469638250317 2
|
2015-09-07 11:44:36 -06:00
|
|
|
*/
|