nus-cs2030 / 2122-s2

CS2030 repository and wiki for AY 2021/2022 Sem 2
MIT License
0 stars 0 forks source link

Anyone solved the RedLight , GreenLight, AmberLight problem? Can you please post your code? #611

Open DikshantDulal opened 2 years ago

calvinseptyanto commented 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);

ghost commented 2 years ago

If you are talking about the cyclic dependency one, you have to make the classes abstract and create anonymous inner classes.