AP Computer Science a Quiz: Impact Of Program Design
20 questions · exam conditions
0:00
Impact Of Program DesignQuestion 1 of 20

A bank is revising its Online Banking Application after an audit found inconsistent balance changes across features. The redesign emphasizes encapsulation using three classes: BankAccount, Transaction, and CustomerProfile. BankAccount stores balance as a private field and exposes deposit and withdraw methods that validate amounts and create a Transaction record for every change. CustomerProfile holds customer information and a list of accounts, but it cannot edit balances directly; it must call account methods. A separate TransferService moves money by calling withdraw on one BankAccount and deposit on another, relying on the built-in validation. The team also adds SavingsAccount extends BankAccount with a minimumBalance rule, overriding withdraw to block withdrawals that break the rule. This keeps account-specific constraints close to the account type. Readability improves because balance changes happen in one place, and maintainability improves because new rules are added by editing BankAccount or a subclass, not every feature. The team accepts a slight performance cost from extra method calls because it prevents invalid balance updates that would be expensive to fix later. Considering the class design, in the scenario, how does encapsulation improve data security?

It hides balances and forces updates through validated methods that always log transactions.
It makes all account fields public so any service can correct mistakes quickly.
It guarantees faster transfers because private fields use less memory.
It prevents bugs by requiring semicolons after every balance update statement.
← Back to quizzes

AP Computer Science a Quiz

AP Computer Science a Quiz: Impact Of Program Design

Practice Impact Of Program Design in AP Computer Science a with focused quiz questions that help you check what you know, review explanations, and build confidence with test-style prompts.

What this quiz covers

This quiz focuses on Impact Of Program Design, giving you a quick way to practice the rules, question types, and explanations that matter most for AP Computer Science a.

How to use this quiz

Try each quiz question before looking at the correct answer. Use the explanations to review missed ideas, then come back to similar questions until the pattern feels familiar.

All questions

Question 1

A bank is revising its Online Banking Application after an audit found inconsistent balance changes across features. The redesign emphasizes encapsulation using three classes: BankAccount, Transaction, and CustomerProfile. BankAccount stores balance as a private field and exposes deposit and withdraw methods that validate amounts and create a Transaction record for every change. CustomerProfile holds customer information and a list of accounts, but it cannot edit balances directly; it must call account methods. A separate TransferService moves money by calling withdraw on one BankAccount and deposit on another, relying on the built-in validation. The team also adds SavingsAccount extends BankAccount with a minimumBalance rule, overriding withdraw to block withdrawals that break the rule. This keeps account-specific constraints close to the account type. Readability improves because balance changes happen in one place, and maintainability improves because new rules are added by editing BankAccount or a subclass, not every feature. The team accepts a slight performance cost from extra method calls because it prevents invalid balance updates that would be expensive to fix later. Considering the class design, in the scenario, how does encapsulation improve data security?

  1. It hides balances and forces updates through validated methods that always log transactions. (correct answer)
  2. It makes all account fields public so any service can correct mistakes quickly.
  3. It guarantees faster transfers because private fields use less memory.
  4. It prevents bugs by requiring semicolons after every balance update statement.

Explanation: This question tests understanding of the impact of class design in AP Computer Science A, focusing on encapsulation and data security in banking systems. Class design involves organizing code into reusable, maintainable, and scalable units through principles such as encapsulation, inheritance, and polymorphism. In the provided scenario, BankAccount keeps balance as a private field and only allows changes through deposit() and withdraw() methods, which validate amounts and create Transaction records for every change. Choice A is correct because it accurately describes how encapsulation improves data security by hiding the balance field and forcing all updates through validated methods that ensure proper logging and prevent invalid operations. Choice B is incorrect because making fields public would compromise data security by allowing unvalidated and unlogged balance changes. To help students: Reinforce that encapsulation creates a protective barrier around sensitive data, ensuring all access goes through controlled channels. Watch for: students thinking that data security means preventing all access rather than controlling and validating access.

Question 2

Considering the class design, a game studio is building a 2D adventure game where players explore levels and fight enemies. The design centers on three classes: GameCharacter, Player, and Enemy. GameCharacter is a superclass that stores private health and position fields and provides methods like takeDamage(amount), move(dx, dy), and isAlive(). Player and Enemy inherit from GameCharacter. Player adds an inventory and a method useItem(item), while Enemy adds an aiType and a method chooseAction(). The team also created an abstract class Attack with an abstract method apply(GameCharacter target). Specific attacks like MeleeAttack and FireballAttack extend Attack and implement apply differently. During combat, CombatSystem stores a list of Attack objects and calls apply on each one without checking its exact type. This keeps combat code short and readable, because CombatSystem does not need separate if-statements for every attack. When designers add a new attack later, they only create a new subclass of Attack; they do not change CombatSystem. The team notes that good class design also helps performance by avoiding repeated code paths and reducing unnecessary checks. Based on the scenario, how does polymorphism in the described classes benefit the program?

  1. It forces every attack to share identical damage values.
  2. It replaces all methods with one method to eliminate complexity.
  3. It allows CombatSystem to call apply() on any Attack subclass. (correct answer)
  4. It mainly speeds execution by reducing memory used by objects.

Explanation: This question tests understanding of the impact of class design in AP Computer Science A, focusing on polymorphism and its benefits in game development. Class design involves organizing code into reusable, maintainable, and scalable units through principles such as encapsulation, inheritance, and polymorphism. In the provided scenario, the Attack class hierarchy demonstrates polymorphism where CombatSystem can call apply() on any Attack subclass without knowing its specific type, allowing different attacks to execute their unique behavior. Choice C is correct because it accurately describes how polymorphism allows CombatSystem to work with any Attack subclass through a common interface, eliminating the need for type-specific code. Choice A is incorrect because it confuses polymorphism with forcing identical behavior, when polymorphism actually enables different behaviors through a common interface. To help students: Reinforce that polymorphism allows objects of different types to be treated uniformly through a common interface while maintaining their unique behaviors. Practice tracing through code where a superclass reference calls overridden methods on different subclass objects.

Question 3

A course management platform includes Course, Student, and Instructor classes. Course has a list of enrolled students and a Gradebook. The platform supports InPersonCourse and OnlineCourse, both extending Course. Each course type calculates participation differently, so both override a method like computeParticipationScore(student). The Gradebook calls computeParticipationScore through a Course reference when generating final grades. The team wants to add HybridCourse later without changing Gradebook. Considering the class design, how does polymorphism in the described classes benefit the program?

  1. It forces all course types to use identical grading rules.
  2. It lets Gradebook call one method while each course type computes scores differently. (correct answer)
  3. It prevents any new subclasses, keeping the system small.
  4. It mainly improves performance by skipping method calls at runtime.

Explanation: This question tests understanding of the impact of class design in AP Computer Science A, focusing on polymorphism and flexibility. Polymorphism allows objects of different types to be treated uniformly through a common interface, while each type can provide its own specific implementation of methods. In the provided scenario, InPersonCourse and OnlineCourse both extend Course and override computeParticipationScore(), allowing each to calculate participation differently while Gradebook can call this method through a Course reference without knowing the specific type. Choice B is correct because polymorphism enables Gradebook to work with any Course subclass (including future HybridCourse) through the same method call, while each course type provides its own appropriate scoring logic. Choice A is incorrect because polymorphism actually allows different implementations rather than forcing identical behavior. To help students: Use concrete examples showing how the same method call produces different results based on the actual object type at runtime. Practice tracing through polymorphic method calls to understand dynamic binding. Watch for: students confusing polymorphism with method overloading or thinking it's primarily about performance rather than design flexibility.

Question 4

A game studio is building a level editor alongside its game, so designers can add new enemies without changing core engine code. The class design includes GameCharacter, Enemy, and Level. GameCharacter stores private position and health and provides move and takeDamage methods. Enemy extends GameCharacter and adds a method chooseAction(Level level). Specific enemies like SlimeEnemy and BossEnemy extend Enemy and override chooseAction differently. Level keeps a list of Enemy objects and calls chooseAction on each enemy during update(), without checking the enemy's exact class. This is polymorphism: Level interacts with the Enemy type, and each subclass decides its behavior. Encapsulation prevents Level from directly changing health, so damage must go through takeDamage, which enforces nonnegative health. The team finds this design easier to maintain because adding a new enemy only requires a new subclass; Level's update loop stays the same. It also improves readability by keeping enemy logic inside enemy classes rather than in Level. Performance remains manageable because the update loop avoids a long chain of type checks, which would grow as more enemy types are added. Based on the scenario, how does polymorphism in the described classes benefit the program?

  1. It allows Level to call one method while each Enemy subclass acts differently. (correct answer)
  2. It forces all Enemy subclasses to share identical chooseAction behavior.
  3. It improves performance by eliminating the need for an update loop in Level.
  4. It improves maintainability by requiring manual casts to every specific enemy type.

Explanation: This question tests understanding of the impact of class design in AP Computer Science A, focusing on polymorphism in game development. Class design involves organizing code into reusable, maintainable, and scalable units through principles such as encapsulation, inheritance, and polymorphism. In the provided scenario, Level maintains a list of Enemy objects and calls chooseAction() on each during updates, with SlimeEnemy and BossEnemy providing different implementations of this method. Choice A is correct because it accurately describes how polymorphism allows Level to call one method (chooseAction) while each Enemy subclass acts differently based on its specific implementation. Choice B is incorrect because polymorphism specifically enables different behaviors for each subclass, not identical behavior. To help students: Emphasize that polymorphism eliminates the need for type-specific code in the calling class, making systems more extensible. Practice adding new enemy types to see how polymorphism allows extension without modifying the Level class.

Question 5

A mid-sized retailer is expanding its Inventory Management System from one warehouse to multiple locations. The system uses Product to represent items, Inventory to track stock, and Order to reserve and ship items. Product keeps quantity private and only changes it through adjustQuantity(int delta), which rejects updates that would make quantity negative. Inventory contains a collection of Product objects and provides reserve(String productId, int amount) used by Order during checkout. Order has a status field (PENDING, COMPLETED, CANCELED) and process(Inventory inv) that first reserves all items; if any reservation fails, it cancels the whole order to avoid partial updates. To support special products, the team adds BulkProduct extends Product with a caseSize field and overrides adjustQuantity so stock changes must be multiples of caseSize. Order and Inventory still work with the Product type, so they don't change when BulkProduct is added. The team discusses scalability: they expect more product types and more rules, but they want minimal edits to core checkout logic. They also care about data consistency: no order should reduce stock below zero, and all stock changes should be validated in one place. This design improves maintainability because rules live in Product and its subclasses, not scattered across Order and Inventory. It also keeps performance acceptable because each reservation does a small, consistent validation step rather than repeated checks in multiple classes. Based on the scenario, which class design feature contributes most to the program's scalability?

  1. Inheritance lets new Product subclasses add rules without changing Order processing code. (correct answer)
  2. Public fields let Inventory update quantities quickly across all classes.
  3. Extra comments in methods automatically prevent inconsistent stock updates.
  4. Using more loops in Order ensures the system supports unlimited product types.

Explanation: This question tests understanding of the impact of class design in AP Computer Science A, focusing on scalability through inheritance. Class design involves organizing code into reusable, maintainable, and scalable units through principles such as encapsulation, inheritance, and polymorphism. In the provided scenario, new product types like BulkProduct can be added as subclasses of Product, implementing their own rules while Order and Inventory continue to work with the Product type without modification. Choice A is correct because inheritance allows new Product subclasses to add specific rules (like BulkProduct's caseSize constraint) without changing the Order processing code, which is the key to scalability. Choice B is incorrect because public fields would violate encapsulation and actually harm scalability by making it harder to enforce consistent rules. To help students: Emphasize that inheritance supports the Open-Closed Principle - classes should be open for extension but closed for modification. Practice identifying how new requirements can be met by adding subclasses rather than modifying existing code.

Question 6

Based on the scenario, a mid-sized online banking application is being refactored for long-term growth. The developers define an Account superclass with private balance and accountNumber fields and methods deposit and withdraw. They create subclasses CheckingAccount, SavingsAccount, and BusinessAccount, each overriding withdraw to enforce different rules (overdraft, minimum balance, or daily limits). A CustomerProfile class stores a private list of Account objects and exposes getAccounts() as a read-only copy to avoid outside edits. A Transaction class stores amount, type, and status, while TransactionService processes transactions by holding an Account reference and calling withdraw or deposit without knowing the specific subclass. The team expects frequent new account types and wants to avoid rewriting transaction logic each time. They also want code that new developers can understand quickly, with fewer duplicated methods. Considering the class design, which class design feature contributes most to the program's scalability?

  1. Polymorphism allows one TransactionService to support many account types. (correct answer)
  2. Public fields allow faster edits by skipping validation methods.
  3. Extra constructors reduce the need for testing new features.
  4. Hard-coding account rules in TransactionService avoids new classes.

Explanation: This question tests understanding of the impact of class design in AP Computer Science A, focusing on polymorphism and its contribution to program scalability. Class design involves organizing code into reusable, maintainable, and scalable units through principles such as encapsulation, inheritance, and polymorphism. In the provided scenario, TransactionService can process any Account subclass (CheckingAccount, SavingsAccount, BusinessAccount) through the Account interface, demonstrating how polymorphism enables the system to handle new account types without modification. Choice A is correct because it accurately describes how polymorphism allows TransactionService to support many account types through a common interface, making the system scalable as new account types are added. Choice B is incorrect because it suggests public fields improve scalability by skipping validation, which would actually compromise data integrity and make the system harder to maintain. To help students: Emphasize that polymorphism is key to building scalable systems that can accommodate new types without modifying existing code. Practice identifying scenarios where polymorphism eliminates the need for type-specific conditional logic.

Question 7

Considering the class design, an educational platform supports multiple course delivery methods. The system uses Course as a superclass with private roster and methods enroll and postAnnouncement. Three subclasses inherit from Course: InPersonCourse stores roomNumber, OnlineCourse stores meetingLink, and HybridCourse stores both. For grading, the platform defines a Grader interface with gradeAssignment(Student s, Assignment a). Different graders implement it: SimpleGrader returns a percent score, while RubricGrader uses categories like clarity and correctness. Each Course stores a Grader reference and calls gradeAssignment through that reference when an instructor submits grades. This design keeps Course focused on managing students and announcements, while grading details stay in grader classes. When a new grading approach is needed, developers add a new Grader implementation without rewriting Course. The team believes this will reduce bugs and keep files shorter and easier to read. Based on the scenario, how does polymorphism in the described classes benefit the program?

  1. It requires every grader to return the same score for fairness.
  2. It lets Course call gradeAssignment on any Grader implementation. (correct answer)
  3. It prevents new delivery methods by locking the Course hierarchy.
  4. It reduces compile-time syntax errors by shortening variable names.

Explanation: This question tests understanding of the impact of class design in AP Computer Science A, focusing on polymorphism through interfaces and its benefits. Class design involves organizing code into reusable, maintainable, and scalable units through principles such as encapsulation, inheritance, and polymorphism. In the provided scenario, the Grader interface allows Course to work with any grading implementation (SimpleGrader, RubricGrader) without knowing the specific type, demonstrating how polymorphism through interfaces enables flexibility and extensibility. Choice B is correct because it accurately describes how polymorphism allows Course to call gradeAssignment() on any Grader implementation, keeping Course focused on its core responsibilities while grading details vary. Choice A is incorrect because it confuses polymorphism with enforcing identical behavior, when polymorphism actually enables different implementations of the same interface. To help students: Reinforce that interfaces define contracts that multiple classes can implement differently, enabling polymorphic behavior. Practice designing systems where different implementations can be swapped without changing the code that uses them.

Question 8

An online bank is adding new transaction types while keeping customer data protected. The system uses CustomerProfile, BankAccount, and Transaction. CustomerProfile stores private personal details and exposes only methods like updateEmail and getMaskedPhone, so other parts of the program cannot read sensitive data directly. BankAccount keeps balance private and updates it only through deposit and withdraw, each creating a Transaction record with type and timestamp. A new BillPaymentTransaction extends Transaction and adds payeeName and confirmationCode, but it still uses the same base fields for amount and time. A TransactionHistory class displays transactions by storing a list of Transaction objects and calling getSummary() on each; BillPaymentTransaction overrides getSummary to include payeeName, while other transactions show different details. This polymorphism keeps the display code short and readable because it does not check the exact transaction type. Maintainability improves because adding a new transaction type mainly requires a new subclass and an updated summary, not changes to TransactionHistory. Performance remains acceptable because the program avoids long type-check chains as transaction types grow. Based on the scenario, how does polymorphism in the described classes benefit the program?

  1. It lets TransactionHistory call getSummary on each Transaction, regardless of subclass. (correct answer)
  2. It blocks new transaction types because all summaries must be identical.
  3. It improves security by making customer details public for easier debugging.
  4. It improves performance by removing the need to store Transaction objects.

Explanation: This question tests understanding of the impact of class design in AP Computer Science A, focusing on polymorphism in transaction processing. Class design involves organizing code into reusable, maintainable, and scalable units through principles such as encapsulation, inheritance, and polymorphism. In the provided scenario, TransactionHistory stores a list of Transaction objects and calls getSummary() on each, with BillPaymentTransaction overriding this method to include additional information like payeeName. Choice A is correct because it accurately describes how polymorphism lets TransactionHistory call getSummary() on each Transaction regardless of its specific subclass, with each type providing its own appropriate summary format. Choice B is incorrect because polymorphism actually enables different summary formats for different transaction types, not blocking new types. To help students: Reinforce that polymorphism allows client code to work with a general interface while getting specific behaviors. Watch for: students thinking polymorphism restricts functionality when it actually enhances flexibility and extensibility.

Question 9

A small game studio is building a 2D adventure game where many characters share common behavior but differ in attacks. The team creates a base class GameCharacter with private fields for health, position, and a method takeDamage(int amount) that prevents health from dropping below zero. Two subclasses extend it: Warrior and Mage. Both inherit movement and health logic, but they override attack(GameCharacter target). Warrior.attack uses a swordDamage value, while Mage.attack uses mana and can apply a burn effect. A third class, BattleSystem, runs fights by storing a list of GameCharacter objects and calling attack on the current attacker without checking its specific type. This is polymorphism: the same method call triggers different behavior depending on the object's class. Encapsulation keeps health safe because only takeDamage can change it, so BattleSystem cannot accidentally set negative health. The design improves readability because BattleSystem stays short and focuses on turn order, not character-specific details. It also improves maintainability because adding a new subclass like Archer requires implementing attack, but BattleSystem does not need changes. Performance is predictable: polymorphism adds a small method-dispatch cost, but it avoids long if/else chains that would grow as more character types are added. Based on the scenario, how does polymorphism in the described classes benefit the program?

  1. It forces BattleSystem to use if/else checks for every character type.
  2. It lets BattleSystem call attack uniformly while each subclass performs its own behavior. (correct answer)
  3. It prevents subclasses from changing behavior, keeping all attacks identical.
  4. It mainly improves performance by eliminating all method calls at runtime.

Explanation: This question tests understanding of the impact of class design in AP Computer Science A, focusing on polymorphism and its benefits. Class design involves organizing code into reusable, maintainable, and scalable units through principles such as encapsulation, inheritance, and polymorphism. In the provided scenario, BattleSystem stores a list of GameCharacter objects and calls attack() on them without checking their specific type, allowing Warrior and Mage to execute their own unique attack implementations. Choice B is correct because it accurately describes how polymorphism enables BattleSystem to call the attack method uniformly on any GameCharacter while each subclass (Warrior, Mage) performs its own specific behavior. Choice A is incorrect because polymorphism specifically eliminates the need for if/else type checks, not forces them. To help students: Emphasize that polymorphism allows a single interface (method call) to trigger different behaviors based on the actual object type at runtime. Practice tracing through code where a parent class reference calls an overridden method to see how the actual object's implementation executes.

Question 10

An online banking application models CustomerProfile, BankAccount, and Transaction. CustomerProfile stores private contact info and exposes updateEmail(newEmail) with a simple format check. BankAccount stores a private balance and logs each Transaction. Transaction objects are immutable after creation, so their amount and timestamp cannot be changed. The app prints monthly statements by iterating transactions and calling getSummary() on each one. Considering the class design, how does the class design in the scenario enhance code maintainability?

  1. It keeps responsibilities separate, so changes to statements rarely affect account rules. (correct answer)
  2. It improves maintainability by avoiding all classes and using only global variables.
  3. It improves maintainability by focusing on shorter variable names everywhere.
  4. It improves maintainability by making every field public for quick edits.

Explanation: This question tests understanding of the impact of class design in AP Computer Science A, focusing on separation of concerns and maintainability. Maintainability refers to how easily code can be understood, modified, and extended over time without introducing bugs or requiring widespread changes. In the provided scenario, each class has a clear, focused responsibility: CustomerProfile manages contact information, BankAccount handles balance and transaction logging, and Transaction objects are immutable records of financial events. Choice A is correct because this separation means changes to statement generation logic won't affect account balance rules, and modifications to email validation won't impact transaction processing, making the codebase easier to maintain and evolve. Choice B is incorrect because avoiding classes and using global variables would create tightly coupled code that's difficult to maintain. To help students: Emphasize the single responsibility principle where each class should have one reason to change. Practice identifying when a class is trying to do too much and how to split responsibilities appropriately. Watch for: students thinking that fewer classes means simpler code, when actually well-separated concerns lead to more maintainable systems.

Question 11

A retailer's Inventory Management System must handle frequent restocks and customer orders while preventing stock from going negative. The team creates Product, Inventory, and Order. Product has private fields productId, name, and quantity, and it provides addStock and removeStock methods that validate inputs. Inventory stores Product objects and offers restock and reserve methods that call Product's methods, keeping all quantity rules inside Product. Order contains line items and processes by asking Inventory to reserve each item; if any reserve fails, the order is not completed. Later, the team adds DigitalProduct extends Product, overriding removeStock so quantity never decreases, because digital items have unlimited supply. Order and Inventory still treat items as Product, so they don't need edits. This improves maintainability because new product types are added by extending Product and overriding behavior, not by rewriting order processing. Readability improves because rules are located in the class responsible for them. Performance stays reasonable because validation happens once per stock change rather than scattered checks across multiple classes. Considering the class design, what role does inheritance play in the class design described?

  1. It allows DigitalProduct to reuse Product data while redefining stock removal behavior. (correct answer)
  2. It removes the need for Inventory because subclasses can store all products automatically.
  3. It improves scalability by forcing Order to know every subclass by name.
  4. It prevents logic errors by making quantity a public field in all subclasses.

Explanation: This question tests understanding of the impact of class design in AP Computer Science A, focusing on inheritance and specialized behavior. Class design involves organizing code into reusable, maintainable, and scalable units through principles such as encapsulation, inheritance, and polymorphism. In the provided scenario, DigitalProduct extends Product and inherits its data fields and methods, but overrides removeStock() to implement unlimited supply behavior while physical products maintain normal stock decrementation. Choice A is correct because it accurately describes how inheritance allows DigitalProduct to reuse Product's data structure and most methods while redefining specific behavior (stock removal) to match its unique characteristics. Choice B is incorrect because inheritance doesn't eliminate the need for Inventory; subclasses define behavior, not storage mechanisms. To help students: Emphasize that inheritance allows selective customization - subclasses can override specific methods while inheriting everything else. Practice identifying which methods need overriding versus which can be inherited as-is.

Question 12

An online banking app uses BankAccount, SavingsAccount, and CheckingAccount. BankAccount defines withdraw(amount) and a protected method canWithdraw(amount). SavingsAccount overrides canWithdraw to enforce a daily limit, and CheckingAccount overrides it to allow overdraft up to a set amount. TransactionLogger records a WithdrawalTransaction whenever withdraw succeeds. The withdraw method calls canWithdraw before updating balance. Considering the class design, how does polymorphism in the described classes benefit the program?

  1. It lets withdraw follow one flow while each account type applies different rules. (correct answer)
  2. It makes all accounts share one balance value, preventing inconsistencies.
  3. It avoids method calls by converting all objects into primitive variables.
  4. It reduces maintenance by removing the need to test account-specific behavior.

Explanation: This question tests understanding of the impact of class design in AP Computer Science A, focusing on polymorphism and the template method pattern. Polymorphism combined with protected methods allows a parent class to define a general algorithm while letting subclasses customize specific steps. In the provided scenario, BankAccount defines the withdraw() method that calls the protected canWithdraw() method, which SavingsAccount and CheckingAccount override to implement their specific withdrawal rules (daily limits vs. overdraft protection). Choice A is correct because this design lets the withdraw() method follow one consistent flow (check permission, update balance, log transaction) while each account type applies its own rules through the polymorphic canWithdraw() method, achieving both consistency and flexibility. Choice B is incorrect because polymorphism is about behavior variation, not sharing data values, and each account maintains its own balance. To help students: Walk through the execution flow showing how withdraw() calls different canWithdraw() implementations based on the actual account type. Practice designing template methods that define algorithms with customizable steps. Watch for: students not understanding how protected methods enable controlled customization points within an inheritance hierarchy.

Question 13

A software development team is designing a library management system. They need to decide between two approaches for representing books: (1) using a single Book class with many instance variables including genre, availability status, and borrower information, or (2) creating separate classes like Fiction, NonFiction, and Reference that inherit from a base Book class, with additional classes for managing availability and borrower data.

Which statement best evaluates the impact of choosing approach (2) over approach (1) on the overall program design?

  1. Approach (2) will always execute faster because inheritance reduces memory usage compared to large objects with many instance variables.
  2. Approach (2) promotes better maintainability and extensibility by separating concerns, but may increase initial development complexity and require more careful interface design. (correct answer)
  3. Approach (2) eliminates the need for polymorphism since each book type will have its own specific methods, making the code simpler to understand.
  4. Approach (2) automatically prevents runtime errors because compile-time type checking ensures that only valid operations are performed on each book type.

Explanation: Choice B correctly identifies that separating classes by responsibility (Single Responsibility Principle) and using inheritance creates more maintainable and extensible code, while acknowledging the trade-off of increased initial complexity. Choice A is incorrect because inheritance doesn't necessarily improve performance and may actually add overhead. Choice C is wrong because approach (2) actually enables polymorphism, not eliminates it. Choice D is incorrect because inheritance doesn't automatically prevent runtime errors, and compile-time checking exists in both approaches.

Question 14

public class StudentRecord { private String name; private int[] testScores; private double gpa;

public StudentRecord(String n, int[] scores) {
    name = n;
    testScores = scores;
    calculateGPA();
}

private void calculateGPA() {
    // implementation not shown
}

public void updateScore(int testNum, int newScore) {
    testScores[testNum] = newScore;
    calculateGPA();
}

}

A programmer suggests modifying the class to make the testScores array public to allow direct access for efficiency. What is the most significant impact this change would have on the program design?

  1. The change would improve performance significantly because public access eliminates method call overhead, making the program more efficient overall.
  2. The change would break encapsulation, allowing external code to modify test scores without updating the GPA, potentially creating inconsistent object states. (correct answer)
  3. The change would require all existing client code to be rewritten because public variables use different syntax than method calls for access.
  4. The change would eliminate the need for the updateScore method entirely, reducing the class size and simplifying the interface for users.

Explanation: Choice B correctly identifies the core issue: breaking encapsulation allows external modification of testScores without triggering calculateGPA(), leading to inconsistent state where GPA doesn't match the scores. Choice A overstates performance benefits and ignores design problems. Choice C is incorrect because existing code using updateScore() wouldn't break, though direct access would use different syntax. Choice D is wrong because updateScore() would still be needed to maintain the invariant that GPA matches test scores.

Question 15

A development team is creating a graphics application where shapes can be drawn, moved, and resized. They are debating whether to use a single Shape class with a type field ("circle", "rectangle", "triangle") and conditional statements for type-specific behavior, or to create separate classes for each shape type with a common interface. Which analysis best describes the long-term impact on program maintainability?

  1. The single class approach is more maintainable because all shape-related code is centralized in one location, reducing the number of files to manage and modify.
  2. The separate classes approach is more maintainable because adding new shapes or modifying existing behavior requires changes to isolated classes rather than modifying conditional statements throughout the single class. (correct answer)
  3. Both approaches are equally maintainable since they represent the same logical structure, and the choice should be based purely on performance considerations.
  4. The single class approach is more maintainable initially, but the separate classes approach becomes more maintainable once more than five different shape types are needed.

Explanation: Choice B correctly applies the Open/Closed Principle - the separate classes approach allows extension (new shapes) without modification of existing code, while the single class approach requires modifying conditional statements throughout the class. Choice A incorrectly values centralization over proper separation of concerns. Choice C is wrong because the approaches have significantly different maintainability characteristics. Choice D incorrectly suggests that maintainability depends on an arbitrary number threshold rather than design principles.

Question 16

public class EmailSystem { private List emailAddresses; private List emailSubjects; private List emailBodies; private List sendDates;

public void addEmail(String address, String subject, String body, Date date) {
    emailAddresses.add(address);
    emailSubjects.add(subject);
    emailBodies.add(body);
    sendDates.add(date);
}

public String getEmailSubject(int index) {
    return emailSubjects.get(index);
}

// similar getter methods for other fields

}

A senior developer suggests replacing this design with an Email class containing address, subject, body, and date fields, and using a single List in EmailSystem. What is the most compelling reason this change would improve the program design?

  1. The new design would eliminate the possibility of data inconsistency that occurs when the parallel lists become out of sync due to programming errors. (correct answer)
  2. The new design would use less memory because a single list requires fewer object references than four separate lists.
  3. The new design would improve performance because accessing related email data would require fewer method calls and list lookups.
  4. The new design would automatically provide thread safety because Email objects are immutable, while parallel lists cannot be safely accessed concurrently.

Explanation: When you encounter questions about data structure design, focus on the fundamental principle of data integrity and how different designs protect against common programming errors. The current design uses parallel lists where related email data is stored across four separate lists at the same index. This creates a fragile system where the lists must remain perfectly synchronized. If a programmer accidentally adds an element to one list but forgets another, or removes elements inconsistently, the data becomes corrupted. For example, if emailAddresses.remove(2) is called but the corresponding elements in other lists aren't removed, all subsequent emails will have mismatched data. Creating an Email class with a single List<Email> eliminates this synchronization problem entirely. Each email's data stays bundled together as one object, making it impossible for the fields to become misaligned. Looking at the wrong answers: B is incorrect because memory usage would likely increase, not decrease—you'd still have the same data plus additional object overhead. C is wrong because performance differences would be minimal and this isn't the primary design concern. D makes false assumptions—the Email objects aren't necessarily immutable, and thread safety isn't automatically provided by object-oriented design. Study tip: On AP Computer Science A questions about design patterns, prioritize data integrity and maintainability over performance optimizations. The exam frequently tests whether you can identify designs that prevent common programming errors, especially those involving data consistency.

Question 17

A development team is creating an inventory management system for a retail store. They need to decide between two approaches for handling different product types (electronics, clothing, books). Approach A uses inheritance with an abstract Product class and concrete subclasses. Approach B uses composition with a Product class containing a ProductType object that defines type-specific behavior.

Which scenario would most strongly favor choosing composition (Approach B) over inheritance (Approach A)?

  1. When products never change categories and each product type has completely different attributes and methods with no shared behavior.
  2. When the development team wants to minimize the number of classes and reduce memory usage by avoiding object composition overhead.
  3. When the system needs to ensure that product objects can be treated polymorphically and different product types share most of their core functionality.
  4. When products need to be categorized by multiple independent criteria (type, brand, price range) and these categorizations may change independently at runtime. (correct answer)

Explanation: When you encounter questions about inheritance versus composition, focus on flexibility and the relationships between objects. This is fundamentally about choosing the right design pattern based on how objects need to interact and change over time. Answer D correctly identifies composition's key strength: handling multiple, independent classification systems that can change at runtime. With composition, a Product object can contain separate objects for ProductType, Brand, and PriceRange, allowing each to vary independently. You could easily reassign a product from "Electronics" to "Smart Home" or from "Budget" to "Premium" without restructuring the entire class hierarchy. This flexibility is composition's superpower. Answer A is backwards - when product types have completely different behaviors with no shared functionality, inheritance actually becomes less valuable since there's little to inherit. This scenario doesn't favor either approach strongly. Answer B misunderstands composition's overhead. While composition does create more objects, the memory difference is typically negligible, and the flexibility gains usually outweigh any minimal performance costs. Modern systems rarely choose design patterns based on such micro-optimizations. Answer C describes inheritance's sweet spot, not composition's. When objects share core functionality and need polymorphic treatment (calling the same methods on different types), inheritance with abstract base classes excels. This is exactly when you'd choose inheritance over composition. Remember this pattern: Choose inheritance when objects share core behavior and have "is-a" relationships. Choose composition when you need flexibility with multiple classification systems or "has-a" relationships. Composition favors runtime flexibility; inheritance favors shared behavior and polymorphism.

Question 18

public class FileProcessor { public void processFile(String filename) { try { // open file // read data // validate data // transform data // generate report // close file } catch (Exception e) { System.out.println("Error processing file"); } } }

A code reviewer suggests breaking this single method into multiple smaller methods for file reading, data validation, data transformation, and report generation. Which statement best describes the primary impact this refactoring would have on program design?

  1. The refactoring would improve performance by reducing method call overhead and eliminating the need to pass data between multiple methods.
  2. The refactoring would make the code more complex and harder to understand by spreading related functionality across multiple methods instead of keeping it centralized.
  3. The refactoring would improve testability, maintainability, and code reuse by allowing individual processing steps to be tested and modified independently. (correct answer)
  4. The refactoring would eliminate the need for exception handling because smaller methods are less likely to throw exceptions than large methods.

Explanation: Choice C correctly identifies the benefits of breaking down large methods: each step can be unit tested independently, modified without affecting others, and potentially reused elsewhere. This applies the Single Responsibility Principle at the method level. Choice A incorrectly claims performance benefits when refactoring typically involves more method calls. Choice B incorrectly suggests that separation of concerns makes code harder to understand. Choice D makes a false claim about exception handling - method size doesn't determine exception likelihood.

Question 19

A programmer is designing a class hierarchy for a game with different types of weapons. Each weapon has damage, range, and durability, but different weapon types calculate damage differently. The programmer considers: (1) an abstract Weapon class with concrete subclasses, or (2) a concrete Weapon class with a weaponType field and switch statements. Which statement best analyzes the impact of these design choices on code flexibility and testing?

  1. Option (1) makes unit testing more difficult because each subclass must be tested separately, while option (2) allows testing all weapon behavior through a single class.
  2. Option (2) provides better flexibility because the weaponType can be changed at runtime, while option (1) requires creating new objects to change weapon types.
  3. Option (1) enables easier unit testing of individual weapon behaviors and better supports adding new weapon types without modifying existing code, while option (2) concentrates changes in switch statements. (correct answer)
  4. Both options provide equivalent flexibility and testability since they model the same real-world concepts, so the choice should depend only on team familiarity with inheritance.

Explanation: Choice C correctly identifies that inheritance (option 1) enables isolated testing of each weapon type and follows the Open/Closed Principle for adding new types. Option (2) requires modifying switch statements throughout the code when adding new weapons. Choice A incorrectly suggests that testing subclasses separately is harder. Choice B confuses weapon type identity with weapon type behavior - changing weapon type typically means creating a different weapon object. Choice D incorrectly claims the approaches are equivalent in flexibility and testability.

Question 20

public class BankAccount { private double balance; private String accountNumber;

public BankAccount(String accNum, double initialBalance) {
    accountNumber = accNum;
    balance = initialBalance;
}

public void deposit(double amount) {
    balance += amount;
}

public void withdraw(double amount) {
    balance -= amount;
}

public double getBalance() {
    return balance;
}

}

A code reviewer suggests that this class design violates important programming principles. Which modification would most effectively address the primary design flaw while maintaining the class's functionality?

  1. Add validation in the withdraw method to prevent negative balances and in the deposit method to reject negative amounts, throwing exceptions for invalid operations. (correct answer)
  2. Make the balance and accountNumber fields public to allow direct access, eliminating the need for getter and setter methods.
  3. Create separate DepositTransaction and WithdrawTransaction classes to handle each operation, removing these methods from BankAccount.
  4. Add a static variable to track the total number of accounts created and provide a method to access this information.

Explanation: Choice A addresses the primary flaw: the class doesn't validate inputs or maintain invariants (like non-negative balance), which can lead to invalid object states. Adding validation ensures the object maintains consistency. Choice B breaks encapsulation and doesn't solve the validation problem. Choice C overly complicates the design without addressing the validation issue. Choice D adds unnecessary functionality that doesn't address the core design flaw of missing validation.