The following question looks at references to objects and th

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\");
   }
}

Solution

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\");
}
}

The following question looks at references to objects and their superclasses. Indicate whether or not the indicated statement is a LEGAL statement (\
The following question looks at references to objects and their superclasses. Indicate whether or not the indicated statement is a LEGAL statement (\

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site