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());
- The String "a" is printed
- The String "b" is printed
- The code compiles but there is a run-time error due to a name collision of the variable
a
- The code won't compile
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".