๐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
- Go to the public template repository for our class: BWL-CS Java Template
- Click the button above the list of files then select
Create a new repository
- Specify the repository name:
CS2-Unit-5-Notes
- Click
Now you have your own personal copy of this starter code that you can always access under the
Your repositories
section of GitHub! - Now on your repository, click and select the
Codespaces
tab - Click
Create Codespace on main
and wait for the environment to load, then youโre ready to code! - ๐ 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
andmyrtle
, 2Turtle
variables and assigned them references to objects created from the classTurtle
and we used instances of JavaโsString
class to assign values to differentString
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
andmyrtle
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 thegetXPos
andgetYPos
onTurtle
.
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 theforward
method changes an instance variablexPos
. When you callforward
onyertle
it changesxPos
on theyertle
object and when you call it onmyrtle
it changes thexPos
on themyrtle
object.
Putting it all together, the three main anatomical features of a class are:
- The instance variables which hold values (attributes) associated with each object
- The constructors whose job is to initialize the instance variables for an object
- 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):
- ๐ 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 theprivate
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 keywordpublic
comes the return type. Thevoid
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
,phoneNumber
but will get the values specific to the object we called
๐ฃ 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.
๐ง 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
โญ๏ธ 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
andprivate
affect the access of classes, data, constructors, and methods. -
The keyword
private
restricts access to the declaring class, while the keywordpublic
allows access from classes outside the declaring class. -
Instance variables are encapsulated by using the
private
access modifier. -
Methods can be
public
orprivate
. The set ofpublic
methods define what other classes can do with an instance of a class.
๐ When class ends, donโt forget to SAVE YOUR WORK!
- Navigate to the
Source Control
menu on the LEFT sidebar - Type a brief commit message in the box, for example:
updated Main.java
- Click the button on the LEFT menu
- Click the button on the LEFT menu
- Finally you can close your Codespace!
Acknowledgement
Content on this page is adapted from Runestone Academy - Barb Ericson, Beryl Hoffman, Peter Seibel.