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 why.



public class RefTest
{
   public static void main(String [] args)
   {
      Carrot c = new Carrot();
      c.sweet();    // 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\");
   }
}

Question options:

1)

ILLEGAL - will not compile

2)

LEGAL - output is \"in vegetable\"

3)

LEGAL - output is \"sweet\"

New

4)

LEGAL - output is \"in carrot\"

5)

LEGAL - output is \"root\"

1)

ILLEGAL - will not compile

2)

LEGAL - output is \"in vegetable\"

3)

LEGAL - output is \"sweet\"

New

4)

LEGAL - output is \"in carrot\"

5)

LEGAL - output is \"root\"

Solution

Answer is :

3)

LEGAL - output is \"sweet\"

Why?

Carrot c = new Carrot();
c.sweet(); // LEGAL

as you can see ... c is object refers to Carrot class

Carrot class has color() and root() methods and so it has been extending from Vegetable class so inherts the method of Vegetable class of color() and sweet()/

so c.sweet(); call sweet() in Vegetable class.

Output is

sweet

3)

LEGAL - output is \"sweet\"

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