6.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!
6.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.
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. Here’s a possible Person class with instance variables, constructor, and methods.
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 the print 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).
Run the following class. Try changing the Person p2 object in main to your name.
6.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.
Instance variables in general should be declared private.
In this case private
means that only the methods in this class can directly access the instance variable values.
Note
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. The methods of the class share the instance variables. They can access and use them.
Once we have created a class like Person, we can have many objects declared 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).
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 (encapsulated in the pink box above).
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.
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; } }
6.1.3. Methods¶
Methods define what an object can do or the behavior of the object. Most methods are public
which means they can be accessed from outside the class. Some methods can be marked as``private`` if they are helper methods that are just used internally by other methods inside the same class. They will not be accessible outside of the class. The private and public keywords determine the external access and visibility of classes, data, constructors, and methods.
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 (also called getters) and mutator (also called setters or modifier) 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, for example p1.print() means 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();
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; } }
6.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. If you want to draw your own, Creately.com is a good free online drawing tool for class diagrams.
When you are given a problem specification, look for the nouns to identify what classes you need to create. For an example, try the problem below.
6-1-4: 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!
6-1-5: 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.
6.1.5. Programming Challenge : Riddle Class¶
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!
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).
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. Hint: Don’t name your instance variables initQuestion and initAnswer – we’ll explain why shortly. 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.
Complete the main method to construct at least 2 Riddle objects and call their printQuestion() and printAnswer() methods to ask and answer the riddle. You can look up some good riddles online.
Complete the Riddle class below and complete the main method to construct 2 Riddle objects and call their printQuestion() and printAnswer() methods.
6.1.6. Practice¶
public String name; private int age; private Cat(String name, int age) { /* implementation not shown */ }
-
Instance variables should be private.
public String name; private int age; private Cat(String name, int age) { /* implementation not shown */ }
-
Instance variables should be private.
private String name; private int age; public Cat(String name, int age) { /* implementation not shown */ }
-
Correct! The instance variables are private and the constructor is public.
public String name; public int age; public Cat(String name, int age) { /* implementation not shown */ }
-
Instance variables should be private.
private String name; private int age; private Cat(String name, int age) { /* implementation not shown */ }
-
Constructor should be public.
6-1-7: Consider the Cat class which will contain a String and an int attribute for a cat’s name and age and a constructor.
public class Cat
{
/* missing code */
}
Which of the following replacements for /* missing code */ is the most appropriate
implementation of the class?
private int numOfPeople; private int volumeOfMusic; private int numOfBoxesOfPizza; public Party() { /* implementation not shown */ } private void startParty() { /* implementation not shown */ }
-
Method startParty() should be public.
private int numOfPeople; private int volumeOfMusic; private int numOfBoxesOfPizza; public Party() { /* implementation not shown */ } public void startParty() { /* implementation not shown */ }
-
Correct, instance variables should be private and the methods should be public.
public int numOfPeople; public int volumeOfMusic; public int numOfBoxesOfPizza; public Party() { /* implementation not shown */ } public void startParty() { /* implementation not shown */ }
-
Instance variables should be private.
private int numOfPeople; private int volumeOfMusic; private int numOfBoxesOfPizza; private Party() { /* implementation not shown */ } private void startParty() { /* implementation not shown */ }
-
Methods should be public.
6-1-8: Consider the Party class below which will contain three int attributes for numOfPeople, volumeOfMusic, and numOfBoxesOfPizza, a constructor, and a startParty method. The startParty method is intended to be accessed outside the class.
public class Party
{
/* missing code */
}
Which of the following replacements for /* missing code */ is the most appropriate
implementation of the class?
6.1.7. 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.