AP Computer Science A · Topic 9.1

Creating Superclasses and Subclasses Practice

Part of Inheritance.

Practice questions

29

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 29 — sign in to practice the rest with adaptive difficulty and mastery tracking.

  1. Sample 1difficulty 2/5

    <code>class Dog extends Animal { }</code> declares

    • A

      Dog as a parent of Animal

    • B

      Dog as a subclass of Animal

      check_circle
    • C

      Animal containing a Dog

    • D

      Compile error

    Why

    <code>extends</code> indicates inheritance: Dog inherits from Animal.

  2. Sample 2difficulty 2/5

    public class Parent {
        protected int x = 5;
    }
    public class Child extends Parent {
        public int doubleX() { return x * 2; }
    }
    // Usage:
    Child c = new Child();
    System.out.print(c.doubleX());

    What is printed?

    • A

      0

    • B

      Compile error: x is private

    • C

      5

    • D

      10

      check_circle

    Why

    x is protected, so Child can access it directly. x = 5, so doubleX() returns 10.

  3. Sample 3difficulty 2/5

    public abstract class Animal {
        public abstract String sound();
    }
    // Usage:
    Animal a = new Animal();

    What occurs?

    • A

      Compiles fine

    • B

      Compiles and creates an Animal with null sound

    • C

      Compile error: Animal is abstract; cannot be instantiated

      check_circle
    • D

      Runtime error when sound() is called

    Why

    Abstract classes cannot be directly instantiated with new. The compiler reports an error.

  4. Sample 4difficulty 2/5

    public class A {
        public int doubleIt(int n) { return n * 2; }
    }
    public class B extends A { }
    System.out.println(new B().doubleIt(7));

    What is printed?

    • A

      Compile-time error

    • B

      7

    • C

      14

      check_circle
    • D

      0

    Why

    B inherits doubleIt from A.

  5. Sample 5difficulty 2/5

    public class Engine { }
    public class Car {
        private Engine e;
        public Car() { e = new Engine(); }
    }

    What relationship does Car have with Engine?

    • A

      has-a (composition)

      check_circle
    • B

      is-a (inheritance)

    • C

      neither

    • D

      is-a abstract

    Why

    Car CONTAINS an Engine as a field — has-a (composition). is-a would require <code>Car extends Engine</code>.