Anatomy of a Class

Help Questions

AP Computer Science A › Anatomy of a Class

Questions 1 - 10
1

Considering the Java class example below, which statement best describes polymorphism?


public class Animal {

  public void speak() {

    System.out.println("...");

  }

}

public class Dog extends Animal {

  @Override

  public void speak() {

    System.out.println("Woof");

  }

}

public class Cat extends Animal {

  @Override

  public void speak() {

    System.out.println("Meow");

  }

}

class Demo {

  public static void main(String[] args) {

    Animal a1 = new Dog();

    Animal a2 = new Cat();

    a1.speak();

    a2.speak();

  }

}

// Encapsulation: hide fields using private.

// Inheritance: Dog and Cat extend Animal.

// Polymorphism: the same call can run different overridden methods.

Based on the class structure presented above, which best describes polymorphism here?

A class must always extend another class

Polymorphism means having multiple constructors

Overriding makes fields public automatically

One method call runs different overridden versions

Explanation

This question tests AP Computer Science A understanding of polymorphism and method overriding in inheritance hierarchies. Polymorphism allows a single method call to execute different implementations based on the actual object type at runtime, enabling flexible and extensible code design. In the example, Animal references (a1 and a2) point to Dog and Cat objects respectively, and when speak() is called, Java's dynamic binding executes the overridden version in each subclass, printing 'Woof' and 'Meow' instead of '...'. Choice A is correct because it accurately describes how polymorphism enables one method call to run different overridden versions based on the actual object type. Choice C is incorrect because it confuses polymorphism with method overloading (multiple methods with the same name but different parameters), which is a compile-time feature rather than runtime behavior. Students should trace through code execution to see how the same method call produces different results. Use visual representations showing how method calls are resolved at runtime based on object type, not reference type.

2

Considering the Java class example below, why is it important to use methods like start() in a class structure?


public class Car {

  private boolean running;

  public Car() {

    running = false; // constructor sets initial state

  }

  public void start() {

    // behavior changes state safely

    running = true;

  }

  public void stop() {

    running = false;

  }

}

// Encapsulation: running is private; methods change it.

// Inheritance: a subclass could extend Car.

// Polymorphism: a subclass could override start().

Based on the class structure presented above, why use methods like start()?

They provide behavior that updates private state

They remove the need for constructors entirely

They make inheritance impossible in the program

They allow fields to be called like functions

Explanation

This question tests AP Computer Science A understanding of methods as the behavior component of classes and their role in encapsulation. Methods like start() encapsulate behavior that safely modifies an object's private state, ensuring that state changes follow defined rules and maintaining object consistency. In the Car class, start() provides a controlled way to change the private running field from false to true, representing the car's engine state in a meaningful way. Choice A is correct because it identifies that methods provide behavior that updates private state, which is fundamental to object-oriented design where objects have both state (fields) and behavior (methods). Choice C is incorrect because methods complement constructors rather than replace them - constructors initialize state while methods modify it during the object's lifetime. Teachers should emphasize that methods represent what objects can do, while fields represent what objects know. Use real-world analogies and have students design classes where methods model realistic behaviors.

3

Considering the Java class example below, how does inheritance benefit the class structure illustrated?


public class Animal {

  public void eat() {

    System.out.println("Eating");

  }

}

public class Dog extends Animal {

  public void fetch() {

    System.out.println("Fetching");

  }

}

// Encapsulation: fields would be private (not shown).

// Inheritance: Dog gets eat() without rewriting it.

// Polymorphism: overridden methods can vary (not shown).

Based on the class structure presented above, how does inheritance help Dog?

Dog automatically gains eat() from Animal

Dog can access all private fields without methods

Dog becomes an interface that cannot be instantiated

Dog must redefine eat() or code will not compile

Explanation

This question tests AP Computer Science A understanding of inheritance and code reuse in class hierarchies. Inheritance allows subclasses to automatically acquire non-private members from their superclass without rewriting code, following the DRY (Don't Repeat Yourself) principle. In the example, Dog extends Animal and automatically inherits the eat() method, so Dog objects can call eat() without the method being defined in the Dog class itself. Choice A is correct because it accurately states that Dog automatically gains the eat() method from Animal through inheritance. Choice C is incorrect because inherited methods don't need to be redefined unless you want different behavior - the code compiles and runs perfectly with Dog using Animal's eat() implementation. Students should understand the difference between inheriting a method and overriding it. Practice creating inheritance hierarchies and testing which methods are available in subclasses to reinforce automatic inheritance of non-private members.

4

Considering the Java class example below, which of the following best describes polymorphism as applied?


public class Animal {

  public void speak() { System.out.println("..."); }

}

public class Dog extends Animal {

  @Override

  public void speak() { System.out.println("Woof"); }

}

public class Cat extends Animal {

  @Override

  public void speak() { System.out.println("Meow"); }

}

class Test {

  public static void makeItSpeak(Animal a) {

    a.speak(); // same call, different results

  }

}

// Encapsulation: fields (if any) stay private.

// Inheritance: Dog/Cat extend Animal.

// Polymorphism: Animal reference can call subclass overrides.

Based on the class structure presented above, which choice best describes polymorphism?

It allows multiple classes to share the same name

It means constructors replace methods entirely

It requires all fields to be public for access

It allows one reference type to use many behaviors

Explanation

This question tests AP Computer Science A understanding of polymorphism as a core object-oriented principle. Polymorphism allows a single reference type to exhibit multiple behaviors through method overriding, where the actual behavior depends on the object's runtime type, not its compile-time reference type. In the example, the makeItSpeak() method accepts an Animal reference but can invoke Dog's or Cat's overridden speak() method, demonstrating how one interface supports many implementations. Choice B is correct because it accurately describes polymorphism as allowing one reference type (Animal) to use many behaviors (different speak() implementations). Choice A is incorrect because it describes name conflicts or overloading rather than polymorphism - polymorphism is about behavior variation, not naming. Teachers should trace through code execution showing how the same method call produces different outputs. Use debugging tools to show students how Java determines which method to call at runtime based on the actual object type.

5

Considering the Java class example below, which access modifier would you use for owner to ensure encapsulation?


public class BankAccount {

  // Fields represent state

  private String owner;

  private double balance;

  public BankAccount(String owner, double startingBalance) {

    this.owner = owner;

    balance = startingBalance;

  }

  public String getOwner() { return owner; }

}

// Encapsulation: hide fields, expose methods.

// Inheritance: subclasses can extend BankAccount.

// Polymorphism: overridden methods can change behavior.

Based on the class structure presented above, which modifier best fits owner?

default, so it cannot be accessed at all

private, so only the class accesses it

protected, so any class in package edits it

public, so other classes can change it freely

Explanation

This question tests AP Computer Science A understanding of access modifiers and encapsulation best practices. The principle of encapsulation dictates that fields should be private to prevent direct external access, with public methods providing controlled access when needed. In the BankAccount class, the owner field contains sensitive account information that should be protected from direct modification, while the getOwner() method provides read-only access. Choice C is correct because private access ensures that only the BankAccount class itself can directly access the owner field, maintaining data integrity and allowing future implementation changes without affecting client code. Choice A is incorrect because protected access would allow any class in the same package or subclasses to modify owner directly, weakening encapsulation. Students should understand that private fields with public getters (and setters when needed) represent the standard Java pattern. Practice identifying which fields need protection and writing appropriate access methods.

6

Considering the Java class example below, what is the purpose of the constructor?


public class Student {

  // Fields

  private String name;

  private int gradeLevel;

  // Constructor

  public Student(String name, int gradeLevel) {

    this.name = name;

    this.gradeLevel = gradeLevel;

  }

  // Method

  public String getName() { return name; }

}

// Encapsulation: private fields, public getters.

// Inheritance: a class can extend Student (not shown).

// Polymorphism: overridden methods can vary (not shown).

Based on the class structure presented above, what does the constructor do?

It initializes name and gradeLevel for new objects

It makes all methods run faster automatically

It prevents objects from being created

It converts fields into methods at compile time

Explanation

This question tests AP Computer Science A understanding of constructor functionality in object initialization. Constructors are special methods that run automatically when objects are created, setting up the initial state by assigning values to instance fields. In the Student class, the constructor takes name and gradeLevel parameters and uses the 'this' keyword to distinguish between parameters and instance fields with the same names, ensuring proper initialization. Choice A is correct because it accurately describes that the constructor initializes the name and gradeLevel fields for new Student objects. Choice D is incorrect because constructors enable object creation rather than prevent it - a class without accessible constructors would prevent instantiation, which is the opposite of this constructor's purpose. Teachers should emphasize the difference between declaring fields and initializing them in constructors. Practice using the 'this' keyword and explain how constructors differ from regular methods in syntax and purpose.

7

Considering the Java class example below, why is it important to use methods like withdraw()?


public class BankAccount {

  private String owner;

  private double balance;

  public BankAccount(String owner, double startingBalance) {

    this.owner = owner;

    balance = startingBalance;

  }

  public boolean withdraw(double amount) {

    // Controlled update to state

    if (amount > 0 && amount <= balance) {

      balance -= amount;

      return true;

    }

    return false;

  }

  public double getBalance() { return balance; }

}

// Encapsulation: methods control how balance changes.

// Inheritance: classes can extend BankAccount (not shown).

// Polymorphism: overridden methods can change behavior (not shown).

Based on the class structure presented above, why use methods like withdraw()?

They rename the class to match the account owner

They enforce rules when changing an object’s state

They allow direct access to private fields from anywhere

They automatically inherit methods from unrelated classes

Explanation

This question tests AP Computer Science A understanding of encapsulation and the importance of controlled access to object state. Methods like withdraw() serve as gatekeepers that validate and control how an object's internal state changes, maintaining data integrity and enforcing business rules. In the BankAccount example, withdraw() prevents invalid operations by checking that the amount is positive and doesn't exceed the balance, returning a boolean to indicate success or failure. Choice A is correct because it identifies that these methods enforce rules when changing object state, which is the essence of encapsulation and data protection. Choice B is incorrect because it contradicts the purpose of encapsulation - methods provide controlled access, not direct access to private fields. Students should practice writing validation logic in methods and understand why direct field access is dangerous. Create scenarios where uncontrolled access would break program logic to reinforce the importance of accessor and mutator methods.

8

Considering the Java class example below, which access modifier best ensures encapsulation for balance?


// BankAccount models a simple account for AP CSA

public class BankAccount {

  // Fields store object state

  private String owner;

  private double balance;

  // Constructor initializes fields

  public BankAccount(String owner, double startingBalance) {

    this.owner = owner;

    balance = startingBalance;

  }

  // Methods provide controlled access/behavior

  public void deposit(double amount) {

    if (amount > 0) balance += amount;

  }

  public boolean withdraw(double amount) {

    if (amount > 0 && amount <= balance) {

      balance -= amount;

      return true;

    }

    return false;

  }

  public double getBalance() { return balance; }

}

// Encapsulation keeps fields hidden and uses public methods.

// Inheritance lets a class extend another class.

// Polymorphism lets overridden methods run based on object type.

Based on the class structure presented above, which modifier should balance use?

public, so all classes can edit it

default, so methods auto-protect it

private, so only this class accesses it

protected, so subclasses can edit it

Explanation

This question tests AP Computer Science A understanding of access modifiers and encapsulation principles in Java class design. Encapsulation is a fundamental OOP principle that protects data by restricting direct access to fields and providing controlled access through methods. In the BankAccount class, the balance field stores sensitive financial data that should only be modified through validated methods like deposit() and withdraw(). Choice C is correct because the private modifier ensures that balance can only be accessed within the BankAccount class itself, preventing external classes from directly manipulating this critical data. Choice A (public) is incorrect because it would allow any class to directly modify balance without validation, breaking encapsulation and potentially causing data corruption. Students should understand that private fields with public getter/setter methods represent the standard pattern for encapsulation in Java. Practice identifying which data needs protection and writing appropriate accessor methods to reinforce this concept.

9

Considering the Java class example below, what is the purpose of the constructor?


// Car represents a real-world car object.

public class Car {

  // Fields describe state

  private String make;

  private String model;

  private int year;

  // Constructor

  public Car(String make, String model, int year) {

    this.make = make;

    this.model = model;

    this.year = year;

  }

  // Methods describe behavior

  public void start() {

    // start the car

  }

  public void stop() {

    // stop the car

  }

}

// Encapsulation keeps fields private and exposes behavior via methods.

// Inheritance and polymorphism allow subclasses to reuse and override methods.

Based on the class structure presented above, what is the purpose of the constructor in the Java class example?​

It deletes objects when they are unused

It overrides methods from a superclass

It initializes the object’s fields at creation

It changes the class name at runtime

Explanation

This question tests AP Computer Science A understanding of constructors and their role in object initialization within Java classes. Constructors are special methods that execute when an object is created using the 'new' keyword, setting up the initial state of the object by assigning values to its fields. In the Car class example, the constructor takes three parameters (make, model, year) and uses them to initialize the corresponding private fields, ensuring every Car object starts with meaningful data. Choice A is correct because it accurately describes the constructor's primary purpose of initializing the object's fields at the moment of creation. Choice C is incorrect because Java uses automatic garbage collection rather than explicit destructors, and constructors have nothing to do with object deletion. Students should practice writing constructors that validate input parameters and understand the difference between constructors and regular methods, noting that constructors have no return type and must match the class name.

10

Considering the Java class example below, which of the following best describes polymorphism as applied?


public class Animal {

  public void speak() { System.out.println("..."); }

}

public class Dog extends Animal {

  @Override

  public void speak() { System.out.println("Woof"); }

}

public class Cat extends Animal {

  @Override

  public void speak() { System.out.println("Meow"); }

}

public class Demo {

  public static void makeItSpeak(Animal a) {

    a.speak(); // same call, different results

  }

}

// Encapsulation: fields would be private with public methods.

// Inheritance: Dog/Cat extend Animal.

Based on the class structure presented above, which of the following best describes polymorphism as applied in the 'Dog' and 'Cat' classes?​

A constructor runs multiple times per method call

A subclass automatically copies fields as public

A method call uses the object’s actual class at runtime

A field can override a method with the same name

Explanation

This question tests AP Computer Science A understanding of polymorphism and dynamic method binding in Java. Polymorphism enables a single method call to exhibit different behaviors based on the actual object type at runtime, even when accessed through a superclass reference - this is the essence of 'many forms' in object-oriented programming. In the example, the makeItSpeak() method accepts an Animal parameter, but when a.speak() is called, Java determines at runtime whether the object is actually a Dog or Cat, executing the appropriate overridden version of speak(). Choice A is correct because it accurately describes dynamic binding: the method call uses the object's actual class (Dog or Cat) at runtime, not the reference type (Animal). Choice D is incorrect because fields and methods exist in separate namespaces in Java - a field cannot override a method, and this statement demonstrates a fundamental misunderstanding of Java's structure. Students should trace through polymorphic method calls using debuggers to see runtime type determination in action.

Page 1 of 2