Creating Superclasses and Subclasses

AP Computer Science A· difficulty 4/5

public class A {
    public int x = 1;
    public int getX() { return x; }
}
public class B extends A {
    public int x = 2;
    public int getX() { return x; }
}
// Usage:
A obj = new B();
System.out.print(obj.x);
System.out.print(" ");
System.out.print(obj.getX());

What is printed?

  • A

    2 1

  • B

    2 2

  • C

    1 1

  • D

    1 2

    check_circle

Explanation

Field access is determined by the declared type (A), so obj.x sees A's x = 1. Method calls use dynamic dispatch, so obj.getX() calls B's version returning B's x = 2.

Want 10 more like this — adaptive to your weak spots?

Related questions