163k views
2 votes
25) What is printed?

public class Inherit
{
class Figure
{
void display( )
{
System.out.println("Figure");
}
}
class Rectangle extends Figure
{
void display( )
{
System.out.println("Rectangle");
}
}
class Box extends Rectangle
{
void display( )
{
System.out.println("Box");
}
}
Inherit( )
{
Figure f = new Figure( );
Rectangle r = new Rectangle( );
Box b = new Box( );
f.display( );
f = r;
((Figure) f).display( );
f = (Figure) b;
f.display( );
}
public static void main(String[ ] args)
{
new Inherit( );
}
}
a) Figure
Rectangle
Box
b) Figure
Figure
Figure
c) Figure
Rectangle
Figure
d) Rectangle
Figure
e) None of the above

1 Answer

2 votes

Final answer:

The output of the code demonstrates polymorphism with 'Figure', 'Rectangle', and 'Box' being printed in sequence, corresponding to the actual objects the references point to.Therefore, the correct answer to what is printed is: a) FigureRectangleBox.

Step-by-step explanation:

The code provided is an example of polymorphism in Java, where a superclass reference is used to refer to a subclass object. The sequence of method calls will exhibit polymorphic behavior, which means the method that gets called is determined by the actual object type (subclass), not the reference type (superclass).

The correct output of the code will be;

  1. Figure - The original object referenced by 'f' is an instance of Figure class.
  2. Rectangle - The reference 'f' now points to an object of Rectangle class. Due to polymorphism, Rectangle's display method is called.
  3. Box - The reference 'f' now points to an object of Box class. Even though 'f' is cast back to Figure, Java's runtime polymorphism calls the Box class's display method.The printed output will be Figure, Rectangle, and Box.
  4. The code creates three objects: f of type Figure, r of type Rectangle, and b of type Box.
  5. When f.display() is called, it prints Figure. When ((Figure) f).display() is called, it prints Rectangle because f is cast to type Figure.
  6. Finally, when f = (Figure) b is executed, f references the object of type Box. Calling f.display() now prints Box as f is referencing an object of type Box.

Therefore, the correct answer to what is printed is: a) FigureRectangleBox.

User Mahdi Tahsildari
by
8.2k points