講義では、このコードを見せられ、二重ディスパッチが作成されると説明されましたが、なぜ無限ループが作成されないのですか?
もし c3po.greet(c4po); TranslationRobot から TranslationRobot メソッドを呼び出します
なぜc5po.greet(c4po); TranslationRobot メソッドではなく CarrierRobot で AbstractRobot メソッドを呼び出してから、TranslationRobot で AbstractRobot メソッドを呼び出さないと、CarrierRobot で AbstractRobot メソッドが呼び出されますか?
AbstractRobot メソッドを呼び出すかどうかを決定するものは何ですか?
AbstractRobot.java
abstract class AbstractRobot extends Robot {
abstract void greet(AbstractRobot other);
abstract void greet(TranslationRobot other);
abstract void greet(CarrierRobot other);
}
CarrierRobot.Java
class CarrierRobot extends AbstractRobot {
...
void greet(TranslationRobot other) {
talk("'Hello from a TranslationRobot to a CarrierRobot.'"); }
void greet(CarrierRobot other) {
talk("'Hello from a CarrierRobot to another.'"); }
void greet(AbstractRobot other) {
other.greet(this);
}}
TranslationRobot.Java
public class TranslationRobot extends AbstractRobot {
...
void greet(TranslationRobot other) {
talk("'Hello from a TranslationRobot to another.'"); }
void greet(CarrierRobot other) {
talk("'Hello from a CarrierRobot to a TranslationRobot.'"); }
void greet(AbstractRobot other) {
other.greet(this);
} }
DispatchWorld.Java
class DispatchWorld {
public static void main (String[] args) {
AbstractRobot c3po = new TranslationRobot();
AbstractRobot c4po = new TranslationRobot();
AbstractRobot c5po = new CarrierRobot();
AbstractRobot c6po = new CarrierRobot();
c3po.greet(c4po);
c5po.greet(c4po);
c4po.greet(c5po);
c5po.greet(c6po);
} }
これにより、次の出力が生成されます。
Standard Model says 'Hello from a TranslationRobot to another.'
Standard Model says 'Hello from a CarrierRobot to a TranslationRobot.'
Standard Model says 'Hello from a TranslationRobot to a CarrierRobot.'
Standard Model says 'Hello from a CarrierRobot to another.'