Consider the inheritance of classes from Exercise R-2.12, and let d be an object variable of type Horse. If d refers to an actual object of type Equestrian, can it be cast to the class Racer? Why or why not?
package Data_Structures.Chapter2;
// Goat class
public class Goat {
int tail;
public void milk() {
System.out.println("milk method in goat");
}
public void jump() {
System.out.println("Jump method in goat");
}
}
// Horse class
public class Horse {
float height;
String color;
public void run() {
System.out.println("running");
}
public void jump() {
System.out.println("Jumping");
}
public static void main(String args[]) {
}
}
public class Pig {
float nose;
public void eat(String food) {
System.out.println("ear in Pig class");
}
public void wallow() {
System.out.println("wallow method in pig");
}
}
public class Racer extends Horse {
public void race() {
System.out.println("Race in Racer");
}
}
public class Equestrain extends Horse {
float weight;
boolean isTrained;
public void trot() {
System.out.println("trot in equestrain");
}
public void isTrained() {
System.out.println("is trained in inequestrain");
}
public static void main(String args[]) {
// below code throws compilation error saying can not cast from Equestrain to Racer
Horse d = (Racer) new Equestrain();
// if you want to call the Racer methods, correct implement is
Racer d1 = new Racer();
d1.race();
}
}
Beacause Racer and Equestrain are diffrent types,
you can resolve the compilation error by Racer extends Equestrain, now Racer becomes
parent class to the Equestrain, and you can cast from Equestrain to Racer.