Learn AP Comp Sci

Problem of the Day

Monday, March 9, 2026


Problem:

Consider the following definitions for classes A and B, where class B inherits from A.

public class A
{
private int x;

public A()
{
x = 1;
}

public int getValue()
{
return x;
}
}


public class B extends A
{
private int x;

public B()
{
x = 2;
}
}

What is the output produced from running the following test program?

public class ABTester
{
public static void main(String[] args)
{
A aObject = new A();
B bObject = new B();
A cObject = new B();
System.out.println(aObject.getValue() + "," +
bObject.getValue() + "," +
cObject.getValue());
}
}
  1. 1 1 1
  2. 1 2 2
  3. 1 2 1
  4. 1 1 2

(Note: This question includes topics that are not currently part of the AP Computer Science A core curriculum.)

Show solution:

The correct answer is a. Although this may appear initially to be an example of polymorphism, in which the superclass method getValue() will work with the variable x from the subclass, that variable is "hidden" by the superclass's x value when that method is executed.

If the getValue method is needed to identify the x in the subclass, there are different ways of achieving that, including writing a getValue method for class B that overrides that of class A.