What is printed by the following code. public class Inherit { public static void
ID: 3575336 • Letter: W
Question
What is printed by the following code. public class Inherit { public static void main(Stringi ] args) { Figure f = new Figure( ); Rectangle r = new Rectangle( ); Box b = new Box( ); f.display( ); f = r; f.display( ); f = b; f.display( ); } } public class Figure { public void display() { System.out.println("Figure"); } } public class Rectangle extends Figure { public void display() { System.out.println("Rectangle"); } } public class Box extendsFigure { public void display() { System.out.println("Box") ; } } Figure Figure Figure Rectangle Box Figure Figure Rectangle Box Box Figure RectangleExplanation / Answer
1. Base Class Figure is defined with a single method display() that prints the statement "Figure".
2. Class Rectangle is inherited from Figure class and overrides method display() that prints the statement "Rectangle".
3. Class Box is inherited from Figure class and overrides method display() that prints the statement "Box".
4. In main method, following objects are created:
(i) an object f is created of Figure class
(i) an object r is created of Rectangle class
(i) an object b is created of Box class
5. Statement f.display() calls display method of Figure class and prints "Figure".
6. Statement f = r; makes the object f to refer Rectangle class
7. So, the statement f.display() calls display method of Rectangle class and prints "Rectangle".
8. Statement f = b; makes the object f to refer Box class
9. So, the statement f.display() calls display method of Box class and prints "Box".
10. So output of given code is :
Figure
Rectangle
Box
So correct option is (C)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.