AP Computer Science a Quiz: Scope And Access
15 questions · exam conditions
0:00
Scope And AccessQuestion 1 of 15

In student records, a StudentRecord class stores studentId and grades to protect sensitive data. The counselor app calls updateGrade to change grades through validation rules. A protected method computeGpa aggregates grades for reports without exposing raw calculations. What is the outcome if grades is changed from private to public?

Outside code can modify grades directly, weakening information hiding.
Only subclasses can read grades, but no code can modify it.
The field becomes accessible only within the same package, not outside it.
The field becomes immutable, so updateGrade no longer compiles.
← Back to quizzes

AP Computer Science a Quiz

AP Computer Science a Quiz: Scope And Access

Practice Scope And Access 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 Scope And Access, 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

In student records, a StudentRecord class stores studentId and grades to protect sensitive data. The counselor app calls updateGrade to change grades through validation rules. A protected method computeGpa aggregates grades for reports without exposing raw calculations. What is the outcome if grades is changed from private to public?

  1. Outside code can modify grades directly, weakening information hiding. (correct answer)
  2. Only subclasses can read grades, but no code can modify it.
  3. The field becomes accessible only within the same package, not outside it.
  4. The field becomes immutable, so updateGrade no longer compiles.

Explanation: This question tests AP Computer Science A concepts, specifically understanding of scope and access control in Java classes. Access control in Java is managed through modifiers like public, private, and protected, which determine the visibility and accessibility of classes, fields, and methods. In this scenario, changing the grades field from private to public removes the protective encapsulation that ensures grade modifications go through proper validation in the updateGrade method. Choice A is correct because making grades public allows any external code to directly read and modify the grades array, bypassing the validation rules in updateGrade and breaking the information hiding principle that protects data integrity. Choice D is incorrect because changing access modifiers doesn't affect mutability - public fields can still be modified unless they are also marked as final. To help students: Demonstrate the dangers of public fields with examples showing how validation can be bypassed. Emphasize that encapsulation isn't just about hiding data, but ensuring it's modified correctly. Watch for: Students thinking that access modifiers affect mutability or that public somehow provides protection.

Question 2

In a library system, Book stores title and author privately to avoid patron edits. The front desk uses public borrowBook and returnBook to enforce rules. A protected calculateOverdueFee supports internal charges. How does the chosen access modifier affect access to the title field?

  1. private restricts direct access to within Book, supporting information hiding. (correct answer)
  2. private allows any class in the package to read title without methods.
  3. private makes title accessible to subclasses only, even outside the package.
  4. private means title cannot be read even inside Book methods.

Explanation: This question tests AP Computer Science A concepts, specifically understanding of scope and access control in Java classes. Access control in Java is managed through modifiers like public, private, and protected, which determine the visibility and accessibility of classes, fields, and methods. In this scenario, the Book class uses private for the title field to prevent external code from directly accessing or modifying book titles, supporting the principle of information hiding. Choice A is correct because private access restricts direct access to the title field to only within the Book class itself, ensuring that any access to the title must go through appropriate methods, thus supporting proper encapsulation and information hiding. Choice D is incorrect because private fields are fully accessible within their own class's methods - if this were true, the field would be useless as the class couldn't work with its own data. To help students: Emphasize that private means 'class-only access,' not 'no access at all.' Show how getter methods can provide controlled read access to private fields. Watch for: The critical misconception that private fields can't be accessed by their own class's methods.

Question 3

In a banking system, BankAccount uses public deposit and withdraw for safe updates. The balance field stays hidden to prevent bypassing overdraft checks. A protected method computeMonthlyInterest supports internal calculations. What access modifier should be used for the balance field in the given scenario?

  1. public, so any class can read and write balance directly.
  2. protected, so all external classes can view balance but not change it.
  3. private, so only BankAccount controls balance changes through methods. (correct answer)
  4. default, so balance is hidden from classes in the same package.

Explanation: This question tests AP Computer Science A concepts, specifically understanding of scope and access control in Java classes. Access control in Java is managed through modifiers like public, private, and protected, which determine the visibility and accessibility of classes, fields, and methods. In this scenario, the BankAccount class needs to protect the balance field from direct external access to ensure all modifications go through methods that enforce overdraft protection and other business rules. Choice C is correct because marking balance as private ensures that only the BankAccount class's own methods (like deposit and withdraw) can access and modify the balance, maintaining complete control over how the balance changes. Choice B is incorrect because protected would still allow subclasses and package members to directly access balance, and it doesn't prevent changes - access modifiers don't create read-only behavior. To help students: Reinforce that sensitive data like financial information should almost always be private. Practice identifying fields that need protection versus methods that need accessibility. Watch for: Misconceptions that access modifiers can create read-only behavior without additional mechanisms.

Question 4

In a library system, a Book class stores title and author while tracking whether it is checked out. The title and author should not be rewritten by patrons, but borrowBook and returnBook must be callable by the front desk app. A protected method calculateOverdueFee helps internal charge tracking. What access modifier should be used for the borrowBook method in this scenario?

  1. private, so only Book can call borrowBook.
  2. protected, so only subclasses can call borrowBook.
  3. public, so outside code can borrow a book through the method. (correct answer)
  4. default, so any class in any package can call borrowBook.

Explanation: This question tests AP Computer Science A concepts, specifically understanding of scope and access control in Java classes. Access control in Java is managed through modifiers like public, private, and protected, which determine the visibility and accessibility of classes, fields, and methods. In this scenario, the Book class needs its borrowBook method to be accessible by the front desk application, which is external code that must interact with the library system. Choice C is correct because the public access modifier allows the borrowBook method to be called from any class, including the front desk app that operates outside the Book class, enabling the core functionality of the library system. Choice A is incorrect because marking borrowBook as private would restrict it to only the Book class itself, preventing the front desk app from borrowing books, which defeats the purpose of the system. To help students: Emphasize that public methods form the interface through which external code interacts with a class. Practice identifying which methods need external access versus internal-only access. Watch for: Students confusing the need for data protection (private fields) with the need for accessible functionality (public methods).

Question 5

In an inventory system, InventoryItem stores itemId and quantity to ensure updates follow business rules. The register uses public addStock and removeStock rather than changing quantity directly. A protected calculateRestockLevel supports internal decisions without UI access. Why is the quantity field marked as private?

  1. It lets any class in the package update quantity without method calls.
  2. It ensures only InventoryItem methods change quantity, supporting validation. (correct answer)
  3. It allows subclasses in other packages to edit quantity directly.
  4. It prevents quantity from being stored in memory until addStock runs.

Explanation: This question tests AP Computer Science A concepts, specifically understanding of scope and access control in Java classes. Access control in Java is managed through modifiers like public, private, and protected, which determine the visibility and accessibility of classes, fields, and methods. In this scenario, the InventoryItem class marks quantity as private to ensure all modifications go through the controlled addStock and removeStock methods which can enforce business rules. Choice B is correct because private access ensures that only methods within the InventoryItem class can directly access and modify quantity, forcing all external code to use the public methods that include proper validation and business logic. Choice A is incorrect because private prevents all external access, including from classes in the same package - package access would require default (no modifier) access level. To help students: Emphasize that private fields with public methods is the standard pattern for encapsulation. Practice identifying what validation might be needed and how private fields protect against invalid states. Watch for: Confusion between private and default package access.

Question 6

public class Employee { private String name; private double salary; protected String department; public String employeeId;

protected Employee(String n, double s, String d, String id) {
    name = n;
    salary = s;
    department = d;
    employeeId = id;
}

public String getName() { return name; }
private void calculateBonus() { /* implementation */ }
protected void changeDepartment(String newDept) {
    department = newDept;
}

}

Consider two scenarios: (1) A Manager class extends Employee in the same package, and (2) A PayrollSystem class in a different package. What is true about constructor and method accessibility?

  1. Neither Manager nor PayrollSystem can instantiate Employee directly, but Manager can access department while PayrollSystem cannot
  2. Both Manager and PayrollSystem can instantiate Employee using the constructor, but only Manager can call changeDepartment()
  3. Manager can call all Employee methods due to inheritance, while PayrollSystem can only call getName() method
  4. Manager can use the Employee constructor and call changeDepartment(), while PayrollSystem cannot instantiate Employee or call changeDepartment() (correct answer)

Explanation: When you encounter questions about access modifiers in Java, focus on how private, protected, public, and package-private affect visibility across different classes and packages. Let's analyze what each class can access. The Employee constructor is protected, meaning it's accessible within the same package and by subclasses. Since Manager extends Employee (inheritance relationship), it can use this constructor even if it's in the same package. The changeDepartment() method is also protected, so Manager can call it through inheritance. PayrollSystem, being in a different package with no inheritance relationship, cannot access the protected constructor to instantiate Employee objects. It also cannot call the protected changeDepartment() method. However, it can access the public field employeeId and the public method getName(). Option A is incorrect because Manager actually can instantiate Employee directly using the protected constructor due to inheritance. Option B is wrong because PayrollSystem cannot use the protected constructor from a different package. Option C is incorrect because Manager cannot access private members like calculateBonus() or the name field directly - inheritance doesn't grant access to private members. Option D correctly identifies that Manager can use the constructor and call changeDepartment() through inheritance, while PayrollSystem cannot do either from a different package without inheritance. Study tip: Remember that protected members are accessible to subclasses regardless of package, but only within the same package for non-subclasses. Always consider both the inheritance relationship and package location when evaluating access.

Question 7

public class BankAccount { private double balance; private String accountNumber; protected int transactionCount;

public BankAccount(String acctNum, double initialBalance) {
    accountNumber = acctNum;
    balance = initialBalance;
    transactionCount = 0;
}

public double getBalance() {
    return balance;
}

protected void incrementTransactions() {
    transactionCount++;
}

}

A programmer creates a subclass called SavingsAccount that extends BankAccount. Within the SavingsAccount class methods, which BankAccount members can be directly accessed without using getter/setter methods?

  1. Only the transactionCount variable can be directly accessed from the subclass methods
  2. The balance variable and incrementTransactions method can both be directly accessed from the subclass methods
  3. The transactionCount variable and incrementTransactions method can both be directly accessed from the subclass methods (correct answer)
  4. All instance variables can be directly accessed, but only public methods can be called from the subclass methods

Explanation: Choice C is correct. In a subclass, protected members (transactionCount variable and incrementTransactions method) can be directly accessed, while private members (balance and accountNumber) cannot be directly accessed. Choice A is incomplete as it doesn't mention the protected method. Choice B is wrong because balance is private. Choice D is wrong because private variables cannot be directly accessed in subclasses.

Question 8

public class Counter { private static int globalCount = 0; private int instanceCount;

public Counter() {
    instanceCount = 0;
    globalCount++;
}

public void increment() {
    instanceCount++;
    globalCount++;
}

public static int getGlobalCount() {
    return globalCount;
}

public int getInstanceCount() {
    return instanceCount;
}

}

Given the Counter class above, which of the following code segments will compile without errors when written in a separate class?

  1. Counter c = new Counter(); System.out.println(c.globalCount + c.instanceCount);
  2. System.out.println(Counter.globalCount); Counter c = new Counter(); System.out.println(c.getInstanceCount());
  3. Counter c = new Counter(); System.out.println(Counter.getGlobalCount() + c.getInstanceCount()); (correct answer)
  4. Counter.increment(); System.out.println(Counter.getGlobalCount());

Explanation: Choice C is correct. Counter.getGlobalCount() correctly calls the static method, and c.getInstanceCount() correctly calls the instance method on an object. Choice A fails because globalCount and instanceCount are private. Choice B fails because globalCount is private and cannot be accessed directly. Choice D fails because increment() is not static and cannot be called on the class name.

Question 9

public class Vehicle { private String model; protected int year; public String color;

private void startEngine() {
    System.out.println("Engine starting");
}

protected void checkMaintenance() {
    System.out.println("Maintenance check");
}

public void drive() {
    startEngine();
    System.out.println("Driving");
}

}

public class Car extends Vehicle { public void performMaintenance() { // Implementation here } }

In the performMaintenance method of the Car class, which of the following statements about accessing Vehicle class members is true?

  1. The year variable and checkMaintenance method can be accessed, but the model variable and startEngine method cannot be accessed (correct answer)
  2. Only the color variable and drive method can be accessed because they are public members of the parent class
  3. The model variable can be accessed directly, but the startEngine method must be called through the drive method
  4. All variables can be accessed directly, but only public and protected methods can be called from the subclass

Explanation: Choice A is correct. Protected members (year variable and checkMaintenance method) are accessible in subclasses, while private members (model variable and startEngine method) are not accessible in subclasses. Choice B is incomplete as it ignores protected members. Choice C is wrong because private variables cannot be accessed directly in subclasses. Choice D is wrong because private variables are not accessible in subclasses.

Question 10

public class GameCharacter { private int health = 100; private int level = 1; protected String weapon = "sword"; public static int totalCharacters = 0;

public GameCharacter() {
    totalCharacters++;
}

private void levelUp() {
    level++;
    health += 20;
}

protected void equipWeapon(String newWeapon) {
    weapon = newWeapon;
}

public void gainExperience() {
    if (Math.random() < 0.5) {
        levelUp();
    }
}

}

A Warrior class extends GameCharacter and is in the same package. Inside a Warrior method, which operations are valid?

  1. Accessing weapon directly, calling equipWeapon(), but not accessing health or calling levelUp() (correct answer)
  2. Accessing totalCharacters directly, calling gainExperience(), but not accessing level or calling levelUp()
  3. Accessing all variables directly since Warrior inherits from GameCharacter within the same package
  4. Calling all methods directly since inheritance provides access to all parent class methods in subclasses

Explanation: Choice A is correct. In the Warrior subclass, protected members (weapon variable and equipWeapon method) are accessible, while private members (health, level, levelUp method) are not accessible even in subclasses. Choice B is incomplete as it doesn't mention the protected members. Choice C is wrong because private variables are not accessible in subclasses regardless of package. Choice D is wrong because private methods are not accessible in subclasses.

Question 11

public class Course { public static final int MAX_STUDENTS = 30; private static int courseCount = 0; private String courseName; protected int enrolledStudents;

public Course(String name) {
    courseName = name;
    enrolledStudents = 0;
    courseCount++;
}

public static int getCourseCount() {
    return courseCount;
}

private boolean isFull() {
    return enrolledStudents >= MAX_STUDENTS;
}

protected void addStudent() {
    if (!isFull()) {
        enrolledStudents++;
    }
}

}

An OnlineCourse class extends Course and is in the same package. Within an OnlineCourse method, which combination of operations is possible?

  1. Read MAX_STUDENTS, modify enrolledStudents directly, and call addStudent(), but cannot call isFull() or access courseCount
  2. Read MAX_STUDENTS and courseCount, call getCourseCount() and addStudent(), but cannot modify enrolledStudents or call isFull()
  3. Access all static variables directly, call addStudent(), but cannot access courseName or call isFull() directly
  4. Read MAX_STUDENTS, access enrolledStudents directly, call addStudent(), but cannot access courseCount or courseName directly (correct answer)

Explanation: Choice D is correct. OnlineCourse can read public MAX_STUDENTS, access protected enrolledStudents, and call protected addStudent(). It cannot access private courseCount or courseName. Choice A is wrong because courseCount access isn't mentioned and isFull() is private. Choice B is wrong because courseCount is private and enrolledStudents can be modified as it's protected. Choice C is wrong because courseCount is private and courseName cannot be accessed.

Question 12

public class Product { private String name; private double price; protected String category; public int inventory;

public Product(String n, double p, String c, int i) {
    name = n;
    price = p;
    category = c;
    inventory = i;
}

public String getName() { return name; }
public double getPrice() { return price; }
protected void updateCategory(String newCategory) {
    category = newCategory;
}

}

Consider three classes: Product (shown above), Electronics extends Product (in the same package), and Store (in a different package). Which statement about member accessibility is correct?

  1. Electronics can access name and category directly, while Store can only access inventory and public methods
  2. Electronics can access category and inventory directly, while Store can access inventory and public methods only (correct answer)
  3. Both Electronics and Store can access category and inventory directly since Electronics inherits from Product
  4. Electronics can access all variables directly due to inheritance, while Store can access category due to package visibility

Explanation: Choice B is correct. Electronics (subclass) can access protected category and public inventory directly, plus public methods. Store (different package) can only access public members: inventory and public methods. Choice A is wrong because name is private. Choice C is wrong because Store cannot access protected category from a different package. Choice D is wrong because Electronics cannot access private name, and Store cannot access protected category from a different package.

Question 13

public class Student { private String name; private int grade; public static int totalStudents = 0;

public Student(String n, int g) {
    name = n;
    grade = g;
    totalStudents++;
}

public void updateGrade(int newGrade) {
    grade = newGrade;
}

private void resetData() {
    name = "Unknown";
    grade = 0;
}

public static void resetCounter() {
    totalStudents = 0;
}

}

Consider the Student class shown above. Which of the following statements about accessing the class members from outside the Student class is correct?

  1. The totalStudents variable can be accessed directly, but the resetData method cannot be called from outside the class (correct answer)
  2. Both the name variable and resetData method can be accessed directly from outside the class if proper syntax is used
  3. The resetCounter method can be called without creating an instance, but the grade variable cannot be accessed directly
  4. All instance variables can be accessed directly, but only public methods can be called from outside the class

Explanation: Choice A is correct. The totalStudents variable is public static, so it can be accessed directly from outside the class using Student.totalStudents. The resetData method is private, so it cannot be accessed from outside the class. Choice B is wrong because name is private and resetData is private. Choice C is wrong because grade is private and cannot be accessed directly. Choice D is wrong because the instance variables name and grade are private.

Question 14

public class MathUtils { public static final double PI = 3.14159; private static int calculationCount = 0;

public static double circleArea(double radius) {
    calculationCount++;
    return PI * radius * radius;
}

private static void resetCount() {
    calculationCount = 0;
}

public static int getCalculationCount() {
    return calculationCount;
}

}

A programmer wants to use the MathUtils class from another class in the same package. Which of the following statements correctly describes what can be accessed?

  1. The PI constant and circleArea method can be accessed, but calculationCount and resetCount cannot be accessed from outside the class (correct answer)
  2. All static members can be accessed using the class name because they are in the same package, regardless of access modifiers
  3. The PI constant can be accessed and modified, while the calculationCount variable can be read but not modified from outside the class
  4. Only the circleArea method and getCalculationCount method can be accessed because they perform operations on the private data members

Explanation: Choice A is correct. PI (public) and circleArea (public) can be accessed from outside the class. calculationCount (private) and resetCount (private) cannot be accessed from outside the class. Choice B is wrong because private members cannot be accessed from outside the class even in the same package. Choice C is wrong because PI is final (cannot be modified) and calculationCount is private (cannot be accessed). Choice D is wrong because getCalculationCount can also be accessed (it's public), and PI constant can be accessed as well.

Question 15

public class Library { private static int totalBooks = 1000; public static String libraryName = "Central Library"; private int memberCount; public int openHours;

public Library(int members, int hours) {
    memberCount = members;
    openHours = hours;
}

public static void updateLibraryName(String name) {
    libraryName = name;
}

private static void adjustBookCount(int change) {
    totalBooks += change;
}

public void addMember() {
    memberCount++;
}

}

From a main method in a different class, which of the following code segments will compile and execute successfully?

  1. Library.libraryName = "New Library"; Library.adjustBookCount(50); System.out.println(Library.totalBooks);
  2. Library.libraryName = "New Library"; Library.updateLibraryName("City Library"); Library myLib = new Library(500, 12); (correct answer)
  3. Library myLib = new Library(500, 12); myLib.memberCount = 600; System.out.println(myLib.openHours);
  4. System.out.println(Library.totalBooks); Library.updateLibraryName("Town Library"); Library myLib = new Library(300, 10);

Explanation: Choice B is correct. libraryName is public static (can be accessed and modified), updateLibraryName is public static (can be called), and the constructor is public (can create instances). Choice A fails because adjustBookCount is private and totalBooks is private. Choice C fails because memberCount is private. Choice D fails because totalBooks is private.