๐Ÿ““5.1: Classes & Objects

Table of Contents


๐Ÿ“– This page is a condensed version of CSAwesome Topic 5.1

Using a GitHub Template for class notes

  1. Go to the public template repository for our class: BWL-CS Java Template
  2. Click the button above the list of files then select Create a new repository
  3. Specify the repository name: CS2-Unit-5-Notes
  4. Click

    Now you have your own personal copy of this starter code that you can always access under the Your repositories section of GitHub!

  5. Now on your repository, click and select the Codespaces tab
  6. Click Create Codespace on main and wait for the environment to load, then youโ€™re ready to code!
  7. ๐Ÿ“ Take notes in this Codespace during class, coding along with the instructor.

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 make your own objects! Watch this video to review the concept of Object-Oriented Programming:

๐Ÿ’ก Remember that a class in Java defines a blueprint for creating objects. When you create objects, you create new instances of that class and what you can do with those instances is determined by what methods are defined in the class.

For example in Unit 2, we created yertle and myrtle, 2 Turtle variables and assigned them references to objects created from the class Turtle and we used instances of Javaโ€™s String class to assign values to different String variables.

Creating a Class

Most classes you write will have the keyword public before them though it is not required. The class definition itself always starts with the keyword class followed by the name of the class. Then the rest of the class, called the body, is defined inside a pair of { }s.

Since weโ€™re talking about anatomy, letโ€™s create a class called Person. Classes are almost always named with capitalized names though this is a matter of style, not a rule of the language. Here is the basic skeleton of a Person class:

public class Person
{
    // define class here - also called the โ€œbodyโ€ of the class

}

You can create instances of the Person class with new as in new Person() And you can declare variables that can hold a reference to a Person object with Person variableName. Put it altogether to declare some variables and initialize each one with a reference to a new Person object as shown here:

// Create OBJECTS - instances of the class
Person ada = new Person();
Person charles = new Person();

So what makes up the body of the classโ€”the stuff between the {}s?

Remember that objects have both attributes and behaviors. These correspond to instance variables and methods in the class definition.

๐Ÿง ๐Ÿ“š The first things we define in a class are usually the instance variables. They are called that because each instance of the class (each object) has its own set of variables that arenโ€™t shared with other instances.

This is what allowed yertle and myrtle from Unit 2 to be at different positions at the same time; they each had their own x position and y position instance variables.

๐Ÿ—๏ธ๐Ÿงฑ The next thing we define in a class is usually its constructors. Weโ€™ll talk about writing constructors in more detail in the next section but a constructorโ€™s job is to initialize the instance variables when the object is created. Usually that will mean they need to take arguments.

๐Ÿ’ƒ๐Ÿ•บ The real meat of a class is in the methods which define the behaviors of the objects of that class.

Recall from Unit 2 that most methods either do things (like the Turtle methods that moved the turtle on the screen) or return values like the getXPos and getYPos on Turtle.

The methods of the class share access to the objectโ€™s instance variables and when a method is called on an object it uses the instance variables for that object.

For example in the Turtle class the forward method changes an instance variable xPos. When you call forward on yertle it changes xPos on the yertle object and when you call it on myrtle it changes the xPos on the myrtle object.

Putting it all together, the three main anatomical features of a class are:

  1. The instance variables which hold values (attributes) associated with each object
  2. The constructors whose job is to initialize the instance variables for an object
  3. The methods who contain the code that gives the objects their behavior and which can use the instance variables defined in the class
public class Person
{
    // 1. INSTANCE VARIABLES

    // 2. CONSTRUCTORS

    // 3. METHODS

}

ADDITIONALLY, any Java class can have a main method which can be used to run that class as a program either to test that one class, or sometimes act as the entry point to a whole program made up of many classes and objects.

One important question we have to ask when designing a class is, what data does it represent? In this case we can ask, what would we want to know about a person? Our answer will depend on what problem we are trying to solve.

In one program, perhaps an address book, we might want to know the personโ€™s name and phone number and email. In another program, such as a medical application, we might need to know their vital signs such as their blood pressure, temperature, and pulse rate.

Instance Variables

As weโ€™ve said, instance variables hold the data for an object. They record what an object needs to know to play its role in the program.

Instance variables are also sometimes called attributes, fields, or properties.

๐Ÿ” In general and definitely on the AP CSA exam, instance variables should be declared private. Think of private as like your diary. Only you should have direct access to it. Similarly, in Java a private instance variable can only be accessed by code in the class that declares the variable.

Instance variables are declared right after the class declaration. They usually 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 declares 3 private instance variables: name, email, and phoneNumber. These are things that you might want to know about a person. They are declared at the top of the class and they exist inside the { } of the class.

Once we have created a class like Person, we can create many instances (objects) of the class. The class is like a blueprint or cookie cutter that defines the variables and methods for that class. Each object will have their own copies of the same instance variables but with possibly different values in them (as seen in the cookie decorations below):

image

  • ๐Ÿ’Š Good Java coding style 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.
  • Why?? Because only code in the class can access or change the values of private instance variables, it is a lot easier to keep track of how your program works than if you had to worry that any code anywhere in a much larger program could possibly change the values of the variables.
  • Code in other classes can only interact with the public methods you provide and cannot directly access the private instance variables (shown in the pink box above).
  • When designing a class you get to decide what data to make accessible or modifiable from other classes by what public methods you provide.

Methods

Now to methods which define what we can actually do with an object. The most important methods in a class are the public methods since they can be accessed from outside the class. You may also write private methods that are not accessible outside of the class and therefore can only be used by other methods inside the same class. As youโ€™ve probably figured out, the public and private keywords determine the external access and visibility of classes, instance variables, constructors, and methods.

Methods define what the object can do. They typically start with the public keyword then a return 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 print method that prints out all the data stored for a person object. Here is what that method definition inside the class file (like peeking into the hood of a car) might look like:

public void print()
{
    System.out.println("Name: " + name);
    System.out.println("Email: " + email);
    System.out.println("Phone Number: " + phoneNumber);
}
  • Notice that this method is marked as public, and after the keyword public comes the return type. The void return type, as you may recall from Unit 2, is used to indicate that the method does not return anything but has some effect such as printing to the screen.
  • After the return type comes the method name followed by parentheses containing the list of parameters. In this case there are no parameters (no input needed for the process) but we still need the ( )s.
  • The body of the method is in { }s.
  • As weโ€™ve discussed, the method can access and use the instance variables defined in the class: name, email, and phoneNumber but will get the values specific to the object we called print on.

๐Ÿ“ฃ To call (activate/run/use) a method, we need to create an object that is an instance of the class such as we get by calling its constructor. Then we use the dot (.) operator to call its public methods, for example p1.print() means call the print method on the object p1.

// 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();

Object-Oriented Design

So far weโ€™ve just talked about designing one class. In object-oriented design (OOD), programmers often start by deciding which classes are needed to solve a problem, and then figure out the data and methods in each class.

When you are given a problem specification, you can identify classes youโ€™ll need by looking for the nouns in the specification.

๐Ÿข For instance, the specification for the turtle graphics system from Unit 2 probably contained a sentence that said something like, โ€œthere are turtles that can exist on a 2-dimensional world and can draw lines by moving around the worldโ€. The main nouns in that description are โ€œturtleโ€ and โ€œworldโ€ and indeed the classes in the system are Turtle and World.

(The one noun that was not turned into a class was โ€œlineโ€. Do you think it would have made sense to create a Line class? Why or why not?)

Once youโ€™ve determined the classes you need, then you can go through the process we described above to design the individual classes.

Note that you can often identify methods that should exist on classes by looking for verbs in the specification, like โ€œmoveโ€.

Drawing Class Diagrams

Sometimes itโ€™s useful, when designing a complex system with lots of classes, to make diagrams of the classes that show you at a glance what instance variables and methods they have. Often these can just be sketches in your notebook or on a whiteboard but there are also more formal systems such as the Unified Modeling Language (UML) for drawing these diagrams.

Here is a tutorial on class diagrams that explains it in more detail if you are curious (drawing class diagrams is not tested on the AP CSA exam). If you want to draw your own, app diagrams or Creately.com are good free online drawing tools for UML class diagrams.

For example, here is a UML class diagram for the Turtle class. The - in front of the attributes indicate that they are private, and the + in front of the methods indicate that they are public.

image

๐Ÿง  Check Your Understanding

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.

๐Ÿ’ป In-Class Activity: Riddle Class

  1. Go to
  2. Make sure you SIGN IN!
  3. Complete the Programming Challenge: Riddle Class activity in pairs.

โญ๏ธ 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. The set of public methods define what other classes can do with an instance of a class.

๐Ÿ›‘ When class ends, donโ€™t forget to SAVE YOUR WORK!

  1. Navigate to the Source Control menu on the LEFT sidebar
  2. Type a brief commit message in the box, for example: updated Main.java
  3. Click the button on the LEFT menu
  4. Click the button on the LEFT menu
  5. Finally you can close your Codespace!

Acknowledgement

Content on this page is adapted from Runestone Academy - Barb Ericson, Beryl Hoffman, Peter Seibel.