5.1. Anatomy of a Java Class

In Unit 2, we learned to use classes and objects that are built-in to Java or written by other programmers. In this unit, you will learn to write your own classes and objects!

5.1.1. Creating a Class

Remember that a class in programming defines a new abstract data type. When you create objects, you create new variables or instances of that class data type. For example in Unit 2, we created yertle and myrtle, 2 turtle objects created from the class Turtle, and we used the Java String class to create different String variables, also called object references.

Here is a fun video demonstrating the difference between the class House which is a blueprint of a house and the objects which are individual houses built from that blueprint. You can think of a class as like a blueprint or a cookie cutter or a factory that produces objects.

Video: (1JJL0YszYik)

To write your own class, you typically start a class declaration with public then class then the name of the class. The body of the class is defined inside a { and a }. For example, the class House below. Then, you can create objects of that new House type by using Classname objectname = new Classname();

public class House
{
   // define class here - a blueprint

}

House myHouse = new House();
House neighborsHouse = new House();

Remember that objects have attributes and behaviors. These correspond to instance variables and methods in the class definition. Instance variables hold the data for objects where as the methods code the behaviors or the actions the object can do. A class also has constructors which initialize the instance variables when the object is created, for example new House() above. And a class can also have a main method which can be used to test the class.

Let’s create a class called Person. What would we want to know about a person? What we want to know depends on what problem we are trying to solve. In one situation, perhaps when creating an address book, we might want to know the person’s name and phone number and email.

Run the code below to see how it constructs 2 Person objects and fills in their data. We will explain all parts of this class in the next sections, but notice that execution always starts in the main method. When a method like the print() method is called, we run the code in that method for that object. After a method is done, the control returns back to the next line of code in the main method. You can also see this in the Java visualizer (click on the link and then Forward at the bottom to run the code step by step).

5.1.2. Instance Variables

Instance Variables hold the data for an object. They record what an object needs to know to do work in the program. Instance Variables are also called attributes, fields, or properties.

All instance variables in general and on the AP CS A exam should be declared private. Think of private as like your diary. Only you should have direct access to it. In this case private means that only the code in this class can directly access the instance variable values.

Note

Instance variables are declared right after the class declaration. They start with private then the type of the variable and then a name for the variable. Private means only the code in this class has access to it.

The Person class above declares 3 instance variables: name, email, and phoneNumber. These are things that you might need to know about a person. They are declared at the top of the class and they exist inside the { } of the class. The methods of the class share the instance variables. They can access and use them.

Object-oriented Programming stresses data encapsulation where the data (instance variables) and the code acting on the data (methods) are wrapped together into a single unit and the implementation details are hidden. The data is protected from harm by being kept private. Anything outside the class can only interact with the public methods and cannot interact directly with the private instance variables. Each time you create a Person object, a new object like the following is created with its own copy of the data and methods.

Person data encapsulation

Figure 1: Data encapsulation in Person

When designing a class, programmers make decisions about what data to make accessible and/or modifiable from an external class. The private access modifier is used to encapsulate and protect the data from external access. Private instance variables can only be accessed by methods within the class in which they are defined.

exercise Check Your Understanding

5-1-1: Click on all the instance variable declarations in the following classRemember, instance variables are private and are declared after the class declaration.
public class Name {

    private String first;
    private String last;

    public Name(String theFirst, String theLast) {
        first = theFirst;
        last = theLast;
     }

     public void setFirst(String theFirst) {
        first = theFirst;
     }

     public void setLast(String theLast) {
        first = theLast;
     }

}

5.1.3. Methods

Methods define what an object can do or the behavior of the object. Most methods are public.

Note

Methods define what the object can do. They typically start with public then a type, then the name of the method followed by parentheses for optional parameters. Methods defined for an object can access and use its instance variables!

The Person class above has a constructor called Person() which we will discuss in the next lesson, a print() method for output, and a main method which runs the whole program. We will also discuss accessor and mutator methods in the next lessons which allow get and set access to the instance variables. Here is an example of the print() method that prints out all the data stored for a person object. Notice that it starts with public and then the return type. The void return type is used to indicate that the method does not return anything. Then it has the method name followed by parentheses for possible parameters. The body of the method is in curly brackets. Notice that the method can access and use the instance variables in the class: name, email, and phoneNumber. The instance variables are shared by all the methods of the class.

public void print()
{
  System.out.println("Name: " + name);
  System.out.println("Email: " + email);
  System.out.println("Phone Number: " + phoneNumber);
}

To call a method to do its job, we create an object of the class and then use the dot (.) operator to call its public methods. Remember that the . is like an ‘s – call p1’s print method.

// call the constructor to create a new person
Person p1 = new Person("Sana", "sana@gmail.com", "123-456-7890");
// call p1's print method
p1.print();

exercise Check Your Understanding

5-1-2: Click on all the parts of the methods in the following classMethods follow the constructor. They include a return type in case they returns something from the method.
public class Name {

    private String first;
    private String last;

    public Name(String theFirst, String theLast) {
        first = theFirst;
        last = theLast;
     }

     public void setFirst(String theFirst) {
        first = theFirst;
     }

     public void setLast(String theLast) {
        first = theLast;
     }

}

5.1.4. Object-Oriented Design

In Object-Oriented Design (OOD), programmers first spend time to decide which classes are needed and then figure out the data and methods in each class. For example, here is the class diagram for the Turtle class that we have seen before. The - in front of the attributes indicate that they are private, and the + in front of the methods indicate that they are public. Here is a tutorial on class diagrams that explains it in more detail if you are curious (Class diagrams are not on the AP CS A exam). If you want to draw your own, Creately.com is a good free online drawing tool for class diagrams.

Turtle class diagram

Figure 2: Turtle Class Diagram

When you are given a problem specification, look for the nouns to identify what classes you need to create. For example, say you were hired to create a program that keeps track of “students at your school and the courses they are taking”, what classes would you create?

exercise Check Your Understanding

5-1-3: You’ve been hired by your school to create a program that keeps track of “students at your school and the courses they are taking”. Name 2 classes that you would create in your program. Name 2 attributes (data kept in instance variables) for each class.

The two nouns in the problem description above, Student and Course would make good class names! Then, you can think about what data you need to keep track of for students and courses and what methods you need. Note that the instance variables in the Person class could also work for a Student class!

exercise Check Your Understanding

5-1-4: Say you wanted to make a computer game from a board game that you are playing. Think about what objects are in the game. For example, here is the description for Monopoly (trademark Hasbro games): “Buy, sell, dream and scheme your way to riches. Players buy, sell and trade to win. Build houses and hotels on your properties and bankrupt your opponents to win it all. Chance and Community Chest cards can change everything.” What classes would you need to create a computer version of this game? (Remember to look for the nouns). Take one of the classes you listed, and try to come up with 2 pieces of data in that class that will be the instance variables.

5.1.5. groupwork Programming Challenge : Riddle Class

Chicken

In this project, you will create a class that can tell riddles like the following:

  • Riddle Question: Why did the chicken cross the playground?

  • Riddle Answer: To get to the other slide!

  1. First, brainstorm in pairs to do the Object-Oriented Design for a riddle asking program. What should we call this class? What data does it need to keep track of in instance variables? What is the data type for the instance variables? What methods do we need? (You could draw a Class Diagram for this class using Creately.com, although it is not required).

  2. Using the Person class above as a guide, write a Riddle class in the Active Code template below that has 2 instance variables for the riddle’s question and answer, a constructor that initializes the riddle, and 2 methods to ask the riddle and answer the riddle. If you came up with other instance variables and methods for this class, you can add those too! Don’t forget to specify the private or public access modifiers. Use the outline in the Active Code below. You will learn how to write constructors and other methods in detail in the next lessons.

  3. Add a main method that constructs at least 3 Riddle objects and calls their methods to ask and answer the riddle. You can look up some good riddles online.

5.1.6. Summary

  • Programmers use code to represent a physical object or nonphysical concept, real or imagined, by defining a class based on the attributes and/or behaviors of the object or concept.

  • Instance Variables define the attributes or data needed for objects, and methods define the behaviors or functions of the object.

  • Data encapsulation is a technique in which the implementation details of a class are kept hidden from the user. The data is kept private with access only through the public methods that can act on the data in the class.

  • The keywords public and private affect the access of classes, data, constructors, and methods.

  • The keyword private restricts access to the declaring class, while the keyword public allows access from classes outside the declaring class.

  • Instance variables are encapsulated by using the private access modifier.

  • Methods can be public or private, but they are usually public.

You have attempted of activities on this page
Next Section - 5.2. Writing Constructors