1) In the context of the Critter example described in class, consider the follow
ID: 3817435 • Letter: 1
Question
1)
In the context of the Critter example described in class, consider
the following code snippets, and answer the following questions.
a.
Does the code compile? If not, explain why.
b.
Does the code execute? If not, explain why.
c.
If the code compiles and executes, what is printed?
// Snippet 1
Critter c = new Poodle();
System.out.println(c instanceof Trainable);
System.out.println( ((Trainable)c).getClass());
// Snippet 2
Critter c = new Buffalo();
Bovine b = c;
System.out.println(c.getClass());
// Snippet 3
Critter c = new Cow();
Trainable t = (Trainable) c;
System.out.println(c instanceof Bovine);
// Snippet 4
Bovine b = new Buffalo();
Critter c = (Buffalo) b;
System.out.println(c.getClass());
////////////////////////////////////////////////////////////////////////////////////////////////
Explanation / Answer
1. // Snippet 1
Critter c = new Poodle();
System.out.println(c instanceof Trainable);
System.out.println( ((Trainable)c).getClass());
Ans: The above Snippet 1 code compiled & executed successfully , prints below output.
true
class Poodle
2. // Snippet 2
Critter c = new Buffalo();
Bovine b = c;
System.out.println(c.getClass());
Ans: The above Snippet 2 fail to compile because Type mismatch: cannot convert from Critter to Bovine.
3. // Snippet 3
Critter c = new Cow();
Trainable t = (Trainable) c;
System.out.println(c instanceof Bovine);
Ans: The above Snippet 3 compiled successfully but throwing exception at execution Cow cannot be cast to Trainable
4. // Snippet 4
Bovine b = new Buffalo();
Critter c = (Buffalo) b;
System.out.println(c.getClass());
Ans: The above Snippet 4 code compiled & executed successfully , prints below output.
class Buffalo
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.