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)
    {
       Vegetable vege = new Vegetable();
       vege.color();    // 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\"
New
3)
LEGAL - output is \"sweet\"
4)
LEGAL - output is \"in carrot\"
5)
LEGAL - output is \"root\"
| 
 | |||
| 
 | |||
| New | |||
| 
 | |||
| 
 | |||
| 
 | 
Solution
answer is
2)
LEGAL - output is \"in vegetable\"
Why?
Vegetable vege = new Vegetable();
 vege.color(); // LEGAL
as you can see ... vege is object refers to Vegetable class
Vegetable class has color() and sweet() methods
so vege.color(); call color() in Vegetable class.
Output is
in vegetable
| 2) | LEGAL - output is \"in vegetable\" | 


