Learn AP Comp Sci

Problem of the Day

Tuesday, April 1, 2025


Problem:

The complete listing of the superclass Alpha is given here.

public class Alpha
{
private String a;

public Alpha()
{
a = "a";
}

public String getValue()
{
return a;
}
}

The complete listing of the subclass Beta which inherits from Alpha is given here.

public class Beta extends Alpha
{
private String a;

public Beta()
{
a = "b"
}
}

What is the result of executing the following instructions?

Beta b = new Beta();
System.out.println(b.getValue());
  1. The String "a" is printed
  2. The String "b" is printed
  3. The code compiles but there is a run-time error due to a name collision of the variable a
  4. The code won't compile

Show solution:

The correct answer is a. The object b is able to access the getValue() method of the superclass, but that method knows nothing about the subclass's instance variable or state. Calling getValue() returns the value of Alpha's instance variable a, which is the string "a".