Unit 3 · 18 min

3.3 Anatomy of a Class

Hide the data, show the behaviors.

Summary, objectives and course and exam description (CED) codes

A class is declared with public class Name and contains private instance variables, public constructors and methods. Data encapsulation keeps the implementation details of a class hidden: private restricts access to the declaring class, while public allows access from other classes. Each object has its own copy of every instance variable.

By the end of this session you can

  • 3.3.A Develop code to designate access and visibility constraints to classes, data, constructors and methods.

3.3.A3.3.A.13.3.A.23.3.A.33.3.A.43.3.A.53.3.A.6

Reviewed against the CED on

Know this already? Jump to the checkpoint.

1LearnThe notes, the traps and how to remember them

1. The parts of a class

In this course, a class is always designated public and is declared with the keyword class 3.3.A.2. Inside, a typical class has three kinds of parts:

Part What it does Access in AP® code
Instance variables Store the attributes of each object private 3.3.A.5
Constructors Set the initial values when an object is created always public 3.3.A.3
Methods Define the behaviors of the object public, or private for helpers 3.3.A.6

Here is a complete class in the AP® free-response “class design” style. Read the comments: they label each part.

public class LibraryBook
{
    // ----- instance variables: private -----
    private String title;
    private int pages;
    private boolean checkedOut;

    // ----- constructor: public, no return type -----
    public LibraryBook(String bookTitle, int numPages)
    {
        title = bookTitle;
        pages = numPages;
        checkedOut = false;
    }

    // ----- accessor methods: public -----
    public String getTitle()
    {
        return title;
    }

    public boolean isCheckedOut()
    {
        return checkedOut;
    }

    // ----- mutator methods: public -----
    public void checkOut()
    {
        checkedOut = true;
    }

    public void returnBook()
    {
        checkedOut = false;
    }

    public void setPages(int numPages)
    {
        if (numPages > 0)
        {
            pages = numPages;
        }
    }

    /** Returns the number of days needed to read the book
     *  at pagesPerDay pages a day. Precondition: pagesPerDay > 0 */
    public int daysToRead(int pagesPerDay)
    {
        return divideRoundUp(pages, pagesPerDay);
    }

    // ----- helper method: private, used only inside the class -----
    private int divideRoundUp(int a, int b)
    {
        return (a + b - 1) / b;
    }

    // ----- toString: returns a String that describes the object -----
    public String toString()
    {
        return title + " (" + pages + " pages)";
    }
}

Client code in another class:

LibraryBook book = new LibraryBook("Ocean Tides", 250);
book.checkOut();
System.out.println(book.getTitle() + " out: " + book.isCheckedOut());
System.out.println(book.daysToRead(30));
System.out.println(book);

Output:

Ocean Tides out: true
9
Ocean Tides (250 pages)

Background: the last line works because println calls the object’s toString method. You will see toString in class code, but writing your own toString (overriding it) is outside the AP® exam, so the exam will not ask you to write one.

2. Encapsulation: public and private

Data encapsulation is a technique in which the implementation details of a class are kept hidden from external classes 3.3.A.1. Two keywords control access to classes, data, constructors and methods 3.3.A.1:

  • private restricts access to the declaring class (the class where it is written) 3.3.A.1.
  • public allows access from classes outside the declaring class 3.3.A.1.

The class above hides how it stores its data. A client cannot see that checkedOut is a boolean; it only sees the behaviors checkOut, returnBook and isCheckedOut. The class could later store the status another way without breaking any client.

3. Each object has its own instance variables

Instance variables belong to the object, and each object has its own copy of each variable 3.3.A.4.

LibraryBook a = new LibraryBook("Ocean Tides", 250);
LibraryBook b = new LibraryBook("Desert Stars", 120);
a.checkOut();
System.out.println(a.isCheckedOut() + " " + b.isCheckedOut());
System.out.println(a + " / " + b);

Output:

true false
Ocean Tides (250 pages) / Desert Stars (120 pages)

Memory after the code runs:

Variable Object it refers to: title pages checkedOut
a “Ocean Tides” 250 true
b “Desert Stars” 120 false

Calling a.checkOut() changed only the checkedOut that belongs to a.

4. Keep instance variables private

Access to attributes should be kept inside the class to accomplish encapsulation, so it is good practice to make instance variables private unless the class specification says otherwise 3.3.A.5. Then the only way to change pages is through setPages, which refuses bad values.

A client that tries to reach a private instance variable directly does not compile:

LibraryBook book = new LibraryBook("Ocean Tides", 250);
book.pages = -5;

Compiler says:

error: pages has private access in LibraryBook

The public mutator is the correct way in, and it protects the data:

LibraryBook book = new LibraryBook("Ocean Tides", 250);
book.setPages(-5);
System.out.println(book);
book.setPages(300);
System.out.println(book);

Output:

Ocean Tides (250 pages)
Ocean Tides (300 pages)

5. Public and private methods

Access to behaviors can be internal or external to the class 3.3.A.6. A public method can be called from inside the class or from other classes. A private method can only be called inside the class 3.3.A.6.

In LibraryBook, the public method daysToRead calls the private helper divideRoundUp. That is allowed because the call is inside the class. A client calling the helper does not compile:

LibraryBook book = new LibraryBook("Ocean Tides", 250);
System.out.println(book.divideRoundUp(250, 30));

Compiler says:

error: divideRoundUp(int,int) has private access in LibraryBook

Watch out: choose private for a method when it is a small step that only the class itself needs, and public when it is a behavior that the class specification promises to other classes.

Lock it in: memory hooks

  • The AP® class recipePublic class, private data, public constructors, public behaviors, private helpers.
  • privateprivate = family only: code inside the declaring class. public = anyone.
  • Instance variablesEvery object gets its own backpack of instance variables.

Common misconceptions

  • "private means other objects of the same class cannot see the data."

    Not quite. private restricts access to the declaring class. Code written inside the class can use the private data; code in other classes cannot.

  • "All objects of a class share the same instance variables."

    Not quite. Instance variables belong to the object. Each object has its own copy, so changing one book's title does not change another book's title.

  • "Methods should always be private, like instance variables."

    Not quite. Methods that other classes need (the behaviors of the object) are public. Helper methods used only inside the class can be private.

Exam traps

  • A client that writes obj.title when title is private gets a compile error, not a run-time error.
  • Do not write private in front of a constructor or a class on the AP® exam: both are always public in this course.
  • A private method can be called inside the class (even by a public method of that class) but never from another class.

2PracticeRecall it, then check yourself

In 30 seconds

  1. In this course, classes are public and declared with the keyword class; constructors are always public.
  2. Data encapsulation hides the implementation details of a class from external classes.
  3. private restricts access to the declaring class; public allows access from outside classes.
  4. Instance variables belong to the object: each object has its own copy.
  5. Make instance variables private unless the specification says otherwise. Methods can be public or private.

Cover this list, say the points out loud, then take the checkpoint without scrolling back up.

Checkpoint · 5 questions

Checkpoint: Anatomy of a Class

Pick an answer to mark it. Every answer is explained, and you can try any question again. Your saved score counts first tries only, and stays in this browser.

  1. 1 Consider the following class. The code segment below the class appears in a method in another class. Which of the following can replace /* missing code */ without causing a compile-time error? 3.3.A.1, 3.3.A.5, 3.3.A.6
    public class Thermostat
    {
        private int target;
    
        public Thermostat(int start)
        {
            target = start;
        }
    
        public int getTarget()
        {
            return target;
        }
    
        public void raise()
        {
            target++;
        }
    
        private boolean tooHot()
        {
            return target > 28;
        }
    }
    
    Thermostat t = new Thermostat(21);
    /* missing code */
    Show answer

    Answer: C. raise is public, so another class can call it. target is a private instance variable, so t.target does not compile in another class, whether it is assigned or read. tooHot is a private method, so it can only be called from inside Thermostat.

  2. 2 A Wallet class needs an attribute that stores the amount of money in each wallet. The specification does not say anything about access. Which declaration best follows the principle of encapsulation? 3.3.A.5
    Show answer

    Answer: B. Instance variables should be private unless the specification says otherwise, so the class keeps control of its data. A public variable lets any class change the balance directly. Adding static makes it a class variable shared by all wallets, so every wallet would have the same balance.

  3. 3 Consider the following class. The code segment below the class appears in a method in another class. What is printed as a result of executing the code segment? 3.3.A.4
    public class Thermostat
    {
        private int target;
    
        public Thermostat(int start)
        {
            target = start;
        }
    
        public int getTarget()
        {
            return target;
        }
    
        public void raise()
        {
            target++;
        }
    }
    
    Thermostat a = new Thermostat(20);
    Thermostat b = new Thermostat(20);
    a.raise();
    a.raise();
    b.raise();
    System.out.println(a.getTarget() + " " + b.getTarget());
    Show answer

    Answer: D. Each object has its own copy of the instance variable target. a is raised twice (20 to 22) and b once (20 to 21). The option 23 23 treats target as if it were shared by both objects, and 22 22 or 21 21 ignore that the two objects were raised a different number of times.

  4. 4 The following method is added inside the Thermostat class from question 1, which has a private method tooHot. Which of the following best describes the result? 3.3.A.1, 3.3.A.6
    public boolean needsCooling()
    {
        return tooHot();
    }
    Show answer

    Answer: C. private restricts access to the declaring class, and needsCooling is written inside Thermostat, so it may call tooHot. The access of the calling method does not matter. Because needsCooling is public, other classes can call it normally; access problems are found by the compiler, never at run time.

  5. 5 Which of the following correctly shows a class header and a constructor header for a Bike class, following the conventions of this course? 3.3.A.2, 3.3.A.3
    Show answer

    Answer: A. In this course, classes are designated public and declared with the keyword class, and constructors are always public. A constructor has no return type: writing void turns it into an ordinary method named Bike, which is not a constructor. Private classes and private constructors are not used in this course.

3PrevailLock it in for exam day

By the numbers

Name each list from memory, then reveal it to check. Each list shows how many items to recall.

Key terms: flip the cards

Read the term, say the definition out loud, then flip to check. Struggling a little to remember is what makes it stick.

  • Anatomy of a classtap to flip

    The parts of a Java class: the class header, instance variables, constructors and methods, each with its access modifier.

    Example and CED codes
  • Encapsulationtap to flip

    Keeping the implementation details of a class hidden from other classes, mainly by making instance variables private.

    Example and CED codes
  • Access modifiertap to flip

    The keywords public and private, which control whether classes, data, constructors and methods can be used from outside the declaring class.

    Example and CED codes
  • Instance variabletap to flip

    An attribute declared in a class outside any method or constructor, whose value is unique to each object of the class.

    Example and CED codes
  • Constructortap to flip

    Code in a class that is called to create an object. It has the same name as the class and sets the object's initial attribute values.

    Example and CED codes
  • toStringtap to flip

    A method that returns a String representing an object; println and string concatenation call it automatically.

    Example and CED codes
  • Classtap to flip

    The formal implementation, or blueprint, of the attributes and behaviors of an object. A class defines a reference type.

    Example and CED codes
  • Objecttap to flip

    A specific instance of a class with defined attributes.

    Example and CED codes
  • Methodtap to flip

    A named block of code that only runs when it is called.

    Example and CED codes

Questions students ask

What are the parts of a class in Java?

A class header (public class Name), instance variables that store each object's attributes, constructors that set the initial state, and methods that define the behaviors.

Why are instance variables private in AP® Computer Science A?

Making them private accomplishes encapsulation: only the class's own code can change the data, so the class controls its values. Other classes use public methods instead.

Can a private method be called?

Yes, but only from code inside the same class. A public method of the class can call a private helper method. Code in another class that calls it does not compile.

What does encapsulation mean?

Data encapsulation is a technique in which the implementation details of a class are kept hidden from external classes, mainly by making instance variables private.

Was this page helpful?

No names are ever shown, and every public comment is checked by us first. Please do not include personal details. To get a reply, email [email protected].

↑ Top

Enlarged view of the selected figure