AP Computer Science A · Topic 9.7

Object Superclass Practice

Part of Inheritance.

Practice questions

12

Want a predicted score for the whole AP CSA exam? Take the 20-question diagnostic and Lumi will plan the rest.

Sample questions

5 of 12 — sign in to practice the rest with adaptive difficulty and mastery tracking.

  1. Sample 1difficulty 2/5

    public class Foo {
    }
    // ...
    Foo f = new Foo();
    Object o = f;

    Which statement is true?

    • A

      Object is a primitive type

    • B

      Foo cannot be assigned to an Object reference

    • C

      Every class implicitly extends Object, so Foo is-a Object

      check_circle
    • D

      Foo cannot inherit from Object because Foo has no superclass

    Why

    All Java classes (other than Object itself) implicitly extend Object, so a Foo reference is assignable to an Object reference.

  2. Sample 2difficulty 3/5

    public class P {
        private int x;
        public P(int x) { this.x = x; }
        public boolean equals(Object o) {
            if (!(o instanceof P)) return false;
            return ((P) o).x == this.x;
        }
    }
    // ...
    P a = new P(3);
    String s = "3";
    System.out.println(a.equals(s));

    What is printed?

    • A

      false

      check_circle
    • B

      true

    • C

      Compile-time error

    • D

      ClassCastException

    Why

    Since s is not an instance of P, equals returns false at the first check.

  3. Sample 3difficulty 3/5

    public class P {
        private int x;
        public P(int x) { this.x = x; }
        public boolean equals(Object o) {
            if (!(o instanceof P)) return false;
            return ((P) o).x == this.x;
        }
    }
    // ...
    P a = new P(3);
    P b = new P(4);
    System.out.println(a.equals(b));

    What is printed?

    • A

      false

      check_circle
    • B

      true

    • C

      3

    • D

      4

    Why

    The x values 3 and 4 differ, so equals returns false.

  4. Sample 4difficulty 3/5

    public class Plain {
        private int x = 5;
    }
    // ...
    Plain p = new Plain();
    String s = p.toString();
    System.out.println(s.startsWith("Plain@"));

    What is printed?

    • A

      Plain@5

    • B

      Compile-time error

    • C

      true

      check_circle
    • D

      false

    Why

    Without overriding, Object's toString returns the form ClassName@hash, so the string starts with "Plain@".

  5. Sample 5difficulty 3/5

    Methods inherited from Object include

    • A

      main, exit

    • B

      add, remove

    • C

      size, length

    • D

      toString, equals, hashCode

      check_circle

    Why

    Object provides toString(), equals(Object), hashCode(), and others.