Access Modifiers
Encapsulation
Constructors
Fix The Error
100

In AP CSA, what access modifier is usually used for instance variables to protect object data?

Private

100

In plain terms, what is encapsulation?

Keeping data private and controlling access through methods.

100

True or False: Constructors have a return type.

False

100

public String name;



private String name;

200

Constructors and methods that need to be called from another class are usually marked with what access modifier?

Public

200

Is getScore() typically an accessor or a mutator?

Accessor

200

For a class named Book, what must the constructor name be?

Book

200

public void getName()

public String getName()

300

Why does this line usually cause a compile error if name is declared correctly inside Student?

System.out.println(s.name);

name is private (cannot be accessed directly from another class).

300

A setScore(int s) method should only allow values from 0 to 100. Write the condition to check that.

s >= 0 && s <= 100

300

What is wrong with this constructor header?

public void Student(String name)

Constructors cannot have a return type (void).

300

public void setAge(int a) {
    age == a;
}

age = a;

400

Rewrite this field declaration so it follows encapsulation best practice. 


public double balance;

private double balance;

400

Why is this a bad accessor for score if the goal is to return the value? 

public void getScore() {
    System.out.println(score);
}

It prints instead of returning the value, and the return type should not be void.

400

Write a constructor header for a class Movie that takes a String title and an int runtime.

public Movie(String title, int runtime)

400

public class Pet {
    private String name;

    public void Pet(String n) {
        name = n;
    }

    public void getName() {
        return name;
    }
}

public Pet(String n) 

and

public String getName()

500

A class has a field age. Write:

  1. the instance variable declaration, and

  2. the accessor header using proper access modifiers.

private int age;
public int getAge()

500

Write a mutator for private int rating; that only updates the field if the new value is from 1 to 5.

public void setRating(int rating) {
    if (rating >= 1 && rating <= 5) {
        this.rating = rating;
    }
}

500

Suppose we have a "soccer player" class and a "team" class. Each player has a team. Each team has a name and a league.

How should the team object be initialized inside the player constructor?

this.team = new team(team.getName(), team.getLeague());
500

public class BankAccount {
    public double balance;

    public BankAccount(double balance) {
        balance = balance;
    }

    public void getBalance() {
        return balance;
    }
}

public class BankAccount {
    private double balance;

    public BankAccount(double balance) {
        this.balance = balance;
    }

    public double getBalance() {
        return balance;
    }
}

M
e
n
u