Open DikshantDulal opened 2 years ago
abstract class TrafficLight { private final String color;
TrafficLight(String color) { this.color = color; } abstract TrafficLight toggle(); @Override public String toString() { return this.color; }
}
abstract class RedLight extends TrafficLight { RedLight() { super("red"); }
@Override TrafficLight toggle() { return new GreenLight(); }
abstract class GreenLight extends TrafficLight { GreenLight() { super("green"); }
@Override TrafficLight toggle() { return new AmberLight(); }
abstract class AmberLight extends TrafficLight { AmberLight() { super("amber"); }
@Override TrafficLight toggle() { return new RedLight(); }
RedLight redLight = new RedLight() { RedLight red = this; @Override TrafficLight toggle() { return new AmberLight() { @Override TrafficLight toggle() { return new GreenLight() { @Override TrafficLight toggle() { return new AmberLight() { @Override TrafficLight toggle() { return red; } }; } }; } }; } }; toggling(redLight, 7);
If you are talking about the cyclic dependency one, you have to make the classes abstract and create anonymous inner classes.
abstract class TrafficLight { private final String color;
}
abstract class RedLight extends TrafficLight { RedLight() { super("red"); }
}
abstract class GreenLight extends TrafficLight { GreenLight() { super("green"); }
}
abstract class AmberLight extends TrafficLight { AmberLight() { super("amber"); }
}
RedLight redLight = new RedLight() { RedLight red = this; @Override TrafficLight toggle() { return new AmberLight() { @Override TrafficLight toggle() { return new GreenLight() { @Override TrafficLight toggle() { return new AmberLight() { @Override TrafficLight toggle() { return red; } }; } }; } }; } }; toggling(redLight, 7);