Learn AP Comp Sci

Problem of the Day

Tuesday, March 10, 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;
}

public int getValue()
{
return x;
}
}

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

Show solution:

The correct answer is b. Here, the getValue method has been defined for superclass A, and overriden in subclass B. For the variable cObject the reference is established to point to an object of class B, so Java uses that class's getValue method, an example of polymorphism.