SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Michael T. Goodrich, Roberto Tamassia, Michael H. Goldwasser
Chapter:
Object-oriented Design
Exercise:
Exercises
Question:13 | ISBN:9781118771334 | Edition: 6

Question

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?

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

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.

0 0

Discussions

Post the discussion to improve the above solution.