191k views
5 votes
Consider the following class definitions.

public class Thing1
{
public void calc(int n)
{
n *= 3;
System.out.print(n);
}
}
public class Thing2 extends Thing1
{
public void calc(int n)
{
n += 2;
super.calc(n);
System.out.print(n);
}
}
The following code segment appears in a class other than Thing1 or Thing2.
Thing1 t = new Thing2();
t.calc(2);
What is printed as a result of executing the code segment?
A. 4
B. 6
C. 68
D. 124
E. 1212

User Derron
by
7.7k points

2 Answers

5 votes

Answer:124

Step-by-step explanation:

User Ermiya Eskandary
by
7.7k points
0 votes

The answer is option D - 124.

The code segment prints '124' as a result of executing the overridden calc() method in Thing2 class after creating a polymorphic reference of type Thing1.

When executing the provided code segment, the output printed is a result of invoking the calc() method on an object of Thing2 class while referencing it as a Thing1 type. The code creates a polymorphic reference of type Thing1 pointing to an instance of Thing2, and when calc(2) is called, the overridden method in Thing2 gets executed. First, n is incremented by 2, resulting in 4, then the super.calc(n) method is called, which multiplies the value by 3, resulting in 12.

Lastly, when returning to the calc() method in Thing2, it prints the updated value of n, which is still 4. Therefore, the sequence printed is 124.

User Masterial
by
8.5k points