109k views
1 vote
28) What is printed by this code?

public class Inherit
{
class Figure
{
void display( )
{
System.out.println("Figure");
}
}
class Rectangle extends Figure
{
void display( )
{
System.out.println("Rectangle");
}
void display(String s)
{
System.out.println(s);
}
}
class Box extends Figure
{
void display( )
{
System.out.println("Box");
}
void display(String s)
{
System.out.println("This is printed: " + s);
}
}
Inherit( )
{
Figure f = new Figure( );
Rectangle r = new Rectangle( );
Box b = new Box( );
f.display( );
f = r;
f.display("one");
f = b;
f.display("two");
}
public static void main(String[ ] args)
{
new Inherit( );
}
}
a) Figure
Rectangle
b) Figure
Rectangle
Figure
Box
c) Figure
Figure
Figure
Figure
d) Rectangle
Figure
Box
Figure
e) Syntax error - this code won't even compile

User Vygintas B
by
8.9k points

1 Answer

4 votes

Final answer:

The code prints 'Figure' because of Java's static binding, and subsequent calls to display(String) on Figure references would actually cause a compile-time error. This is due to these methods with String arguments not being defined in the Figure class.

Step-by-step explanation:

This Java code defines a class Inherit with three inner classes Figure, Rectangle, and Box, where Rectangle and Box extend Figure. Each class has a display() method that prints a string. The special characteristic of method overriding is showcased when assigning subclasses' objects to a superclass reference.

When executing this code, the following occurs:

  • The display() method in Figure is called on a Figure instance, hence 'Figure' is printed.
  • Rectangle overrides display(), but since we're calling display(String) on a Figure reference pointing to a Rectangle object, Java's static binding chooses the Figure's version of display() without an argument, so nothing is printed because Figure doesn't have display(String).
  • Similarly, for Box, the display(String) method isn't called because Box is assigned to a Figure reference, and Figure doesn't define display(String).

The correct answer is a) 'FigureRectangle', however, it is important to note that the question may include a typo. Since the display() method in class Rectangle and Box does not override the display() method with a String argument from the superclass, the actual output will just be 'Figure' as the other calls to display(String) using a Figure reference would lead to a compile-time error.

User Yves Delerm
by
8.0k points