class Animal {
public void fazBarulho() {
System.
out.
println("silêncio"); }
}
class Dog extends Animal {
public void fazBarulho() {
}
}
class Cat extends Animal {
public void fazBarulho() {
}
}
class Ideone {
public static void main
(String[] args
) { Dog dog = new Dog();
Animal animal = new Animal();
Animal animal2 = new Dog();
Animal animal3 = new Cat();
dog.fazBarulho();
animal.fazBarulho();
animal2.fazBarulho(); //concretamente é um cachorro
animal3.fazBarulho(); //concretamente é um gato
System.
out.
println("-- Castings agora --"); ((Animal)dog).fazBarulho(); //upcasting
((Dog)animal2).fazBarulho(); //downcasting, funciona
((Dog)animal3).fazBarulho(); //downcasting, dá erro porque um gato não é um cachorro
((Dog)animal).fazBarulho(); //downcasting, dá erro aqui
}
}
Y2xhc3MgQW5pbWFsIHsgCiAgICBwdWJsaWMgdm9pZCBmYXpCYXJ1bGhvKCkgewogICAgICAgIFN5c3RlbS5vdXQucHJpbnRsbigic2lsw6puY2lvIik7CiAgICB9Cn0KY2xhc3MgRG9nIGV4dGVuZHMgQW5pbWFsIHsgCiAgICBwdWJsaWMgdm9pZCBmYXpCYXJ1bGhvKCkgewogICAgICAgIFN5c3RlbS5vdXQucHJpbnRsbigiYXUgYXUiKTsKICAgIH0KfQpjbGFzcyBDYXQgZXh0ZW5kcyBBbmltYWwgeyAKICAgIHB1YmxpYyB2b2lkIGZhekJhcnVsaG8oKSB7CiAgICAgICAgU3lzdGVtLm91dC5wcmludGxuKCJtaWF1Iik7CiAgICB9Cn0KY2xhc3MgSWRlb25lIHsKICAgIHB1YmxpYyBzdGF0aWMgdm9pZCBtYWluKFN0cmluZ1tdIGFyZ3MpIHsKICAgICAgICBEb2cgZG9nID0gbmV3IERvZygpOyAgICAgIAogICAgICAgIEFuaW1hbCBhbmltYWwgPSBuZXcgQW5pbWFsKCk7CiAgICAgICAgQW5pbWFsIGFuaW1hbDIgPSBuZXcgRG9nKCk7CiAgICAgICAgQW5pbWFsIGFuaW1hbDMgPSBuZXcgQ2F0KCk7CiAgICAgICAgZG9nLmZ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