The following question looks at references to objects and their superclasses. In
ID: 3941279 • Letter: T
Question
The following question looks at references to objects and their superclasses. Indicate whether or not the indicated statement is a LEGAL statement ("will it compile?"). If it is legal, then give the output generated by that statement and explain why.
public class RefTest
{
public static void main(String [] args)
{
Carrot bunny = new Carrot();
Vegetable vege = bunny;
vege.root(); // LEGAL?
}
}
class Vegetable
{
public void color()
{
System.out.println("in vegetable");
}
public void sweet()
{
System.out.println("sweet");
}
}
class Carrot extends Vegetable
{
public void color()
{
System.out.println("in carrot");
}
public void root()
{
System.out.println("root");
}
}
Explanation / Answer
Sorry it is not legal to use vege.root();
because root() doesn't belongs to carrot class so to access it you need to use carrot obj
example
Carrot bunny = new Carrot();
Vegetable vege = bunny;
bunny.root(); // LEGAL
i have used bunny obj to call root(), it works perfectly
output:
root
Here is complete code:
public class HelloWorld
{
public static void main(String [] args)
{
Carrot bunny = new Carrot();
Vegetable vege = bunny;
bunny.root(); // LEGAL?
}
}
class Vegetable
{
public void color()
{
System.out.println("in vegetable");
}
public void sweet()
{
System.out.println("sweet");
}
}
class Carrot extends Vegetable
{
public void color()
{
System.out.println("in carrot");
}
public void root()
{
System.out.println("root");
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.