5 Steps to a 5 AP Computer Science A 2017 (2016)
Review the Knowledge You Need to Score High
Classes and Objects (Basic Version)
IN THIS CONCEPT
Summary: This is a big one. If you don’t understand this concept, you will fail the AP Computer Science A Exam. This chapter introduces you to the most fundamental object-oriented features of Java. It explains the relationship between an object and a class. It also describes the simplest form of a class and the minimal requirements needed to make one. More advanced aspects of classes and objects will be discussed in Concept 7.
Java is an object-oriented programming language whose foundation is built on classes and objects.
A class describes the characteristics of any object that is created from it.
An object is a virtual entity that is created using a class as a blueprint.
Objects are created to store and manipulate information in your program.
An instance variable is used to store an attribute of an object.
A method is an action that an object can perform.
The keyword new is used to create an object.
A reference variable stores the address of the object, not the object itself.
Overview of the Relationship Between Classes and Objects
The intent of an object-oriented programming language is to provide a framework that allows a programmer to manipulate information after storing it in an object. The following paragraphs describe the relationship between many different vocabulary terms that are necessary to understand Java as an object-oriented programming language. The terms are so related that I wanted to describe them all together rather than in separate pieces.
Warning: Proceed with Caution
The next set of paragraphs includes many new terms. You may want to reread this section many times. If you expect to earn a 5 on the exam, you must master everything that follows. Challenge yourself to learn it so well that you can explain this entire chapter to someone else.
Java classes represent things that are nouns (people, places, or things). A class is the blueprint for constructing all objects that come from it. The attributes of the objects from the class are represented using instance variables . The values of all of the instance variables determine the state of the object. The state of an object changes whenever any of the values of the instance variables change. Methods are the virtual actions that the objects can perform. They may either return an answer or provide a service.
Objects are created using the class that holds the blueprint of the object. The class contains a piece of code called a constructor , which tells the computer how to build (construct) an object from that class. The keyword new is used whenever the programmer wants to create an object from a class. When new is followed by the name of a constructor of a class, a new object is created. The action of constructing an object is also referred to as instantiating an object and the object is referred to as an instance of the class. In addition to creating the new object, a reference to the object is created. The object reference variable holds the memory address of the newly created object and is used to call methods that are contained in the object’s class.
This is a really important concept in Java, so here are a few examples of classes. Your challenge is to think of other examples as you wander through your day.
The class Declaration
When you design your own class, you must create a file that contains the class declaration . The name of the class is identified in this declaration. By Java naming convention, a class name always starts with an uppercase letter and is written in camel case.
Create a class called the Circle class:
The virtual attributes that describe an object of a class are called its instance variables . A class can have as many instance variables of any data type as it wants as long as they describe some characteristic or feature of an object of the class. Unlike local primitive variables, default values are assigned to primitive instance variables when they are created (int variables are 0, doubles are 0.0, and booleans are false.) The phrase has-a refers to the instance variables of a class as in: an objectName has-a instanceVariableName.
Every Circle object has-a radius so create an instance variable called radius:
private Versus public Visibility
The words private and public are called visibility modifiers (or access level modifiers ). Using the word private in an instance variable declaration ensures that other classes do not have access to the data stored in the variable without asking the object to provide it. Using the word public in the class declaration ensures that any programmer can make objects from that class.
private Versus public
On the AP Computer Science A Exam, always give instance variables private access visibility. This ensures that the data in these variables is hidden.
Constructors are the builders of the virtual objects from a class. They are used in combination with the keyword new to create an object from the class. Constructors have the same name as the class and are typically listed near the top of a class.
The constructor is the code that is called when you create a new object. When you define a new class, it comes with no-argument constructor . Depending on the IDE that you use, you may or may not see it. It is generally recommended that you write one anyway, especially when you are first learning classes.
The No-Argument Constructor
The no-argument constructor gets its name because no information is passed to this constructor when creating a new object. It is the constructor that allows you to make a generic object from a class.
Parameterized Constructors and Parameters
If you will know some information about an object prior to creating it, then you may want to write a parameterized constructor in your class. You use the parameterized constructor to give initial values to the instance variables when creating a brand-new object. The parameters that are defined in the parameterized constructor are placed in a parameter list and are on the same line as the declaration of the constructor.
The process of sending the initial values to the constructor is called passing a parameter to the constructor. The actual value that is passed to the constructor is called an argument (or actual parameter ) and the variable that receives the value inside the constructor is called the formal parameter . You include a line of code in the parameterized constructor that assigns the value of the formal parameter to the instance variable.
If you choose to write a parameterized constructor for a class, then the default, no-argument constructor vanishes. This is why it is generally recommended that you simply write your own.
Write the no-argument constructor and one parameterized constructor for the Circle Class. The parameterized constructor must have a parameter variable for the radius of a circle.
Parameters in the Parameter List
A parameter is a variable that is located in a parameter list in the constructor declaration. A pair of parentheses after the name of the constructor encloses the entire parameter list.
For example, the parameterized constructor for the Circle class has one parameter variable in its parameter list. The name of the parameter is rad (short for radius) and its data type is a double. The no-argument constructor for the Circle class does not have any parameters in its parameter list.
The real power of an object-oriented programming language takes place when you start to manipulate objects. A method defines an action that allows you to do these manipulations. A method has two options. It may simply perform a service of some kind, or it may compute a value and give the answer back. The action of giving a value back is called returning a value.
Methods that simply perform some action are called void methods. Methods that return a value are called return (or non-void ) methods. Return methods must define what data type they will be returning and include a return statement in the method. A return method can return any kind of data type.
Using the word public in the method declaration ensures that the method is available for other objects from other classes to use.
The return Statement on the AP Computer Science A Exam
Methods that are supposed to return a value must have a reachable return statement. Methods that are void do not have a return statement. This is a big deal on the free-response questions of the AP Computer Science A Exam as you will lose points if you include a return statement for a void method or a constructor.
Accessor and Mutator Methods
When first learning how to write methods for a class, beginning programmers learn two types of methods:
- Methods that allow you to access the values stored in the instance variables
- Methods that allow you to modify the values of the instance variables
Methods that return the value of an instance variable are called accessor (or getter ) methods. Methods that change the value of an instance variable are called mutator (or modifier or setter ) methods. Methods that don’t perform either one of these duties are simply called methods.
Is My Carbonated Soft Drink a Soda, a Pop, or a Coke?
These all refer to the same thing, it just depends on where you live. In a similar way, the methods that retrieve the instance variables of a class can be referred to as accessor or getter methods. The methods that change the value of an instance variable can be called modifier, mutator, or setter methods.
Declaring a Method
Methods are declared using a line of code called a method declaration statement. The declaration includes the access modifier, the return type, the name of the method, and the parameter list. The method signature only includes the name of the method and the parameter list.
General Form of a Method Declaration
Methods should have only one goal. The name of the method should clearly describe the purpose of the method.
Write an accessor method for the radius, a mutator method for the radius, and a method that calculates and returns the area of the circle.
Java Ignores Spaces
Java ignores all spacing that isn’t relevant. The compiler doesn’t care how pretty the code looks in the IDE; it just has to be syntactically correct. On the AP exam, you will sometimes see code that has been streamlined to save space on the page.
For example, the getRadius method for the Circle class could appear like this on the exam:
Putting It All Together: The Circle and CircleRunner Classes
I’m now going to combine the Circle class that we just created with another class to demonstrate code that follows an example of two classes interacting in an object oriented setting. The Circle class defined how to make a Circle object. The CircleRunner class is where the programmer creates virtual Circle objects and then manipulates them.
Summary of the Circle Class
Every circle has-a radius, so the Circle class defines an instance variable called radius. The class also has two constructors as ways to build a Circle object. The no-argument constructor is used whenever you don’t know the radius at the time that you create the Circle object. The radius gets the default value for a double, which is 0.0. The parameterized constructor is used if you know the radius of the circle at the time you construct the Circle object. You pass the radius when you call the parameterized constructor and the constructor assigns the value of its parameter to the instance variable.
The Circle class also has three methods:
- The first method, getRadius, returns the radius from that object. Since the method is getting the radius for the programmer, it is called an accessor (or getter) method.
- The second method, setRadius, is a void method that sets the value of the radius for the object. It is referred to as a modifier (or mutator or setter) method. This method has a parameter, which is a variable that receives a value that is passed to it when the method is called (or invoked) and assigns this value to the instance variable.
- Finally, the third method, getArea, calculates and returns the area of the circle using the object’s radius.
Summary of the CircleRunner Class
The Circle class can’t do anything all by itself. To be useful, Circle objects are created in a class that is outside of the Circle class. Each object that is created from a class is called an instance of the class and the act of constructing an object is called instantiating an object. A class that contains a main method is sometimes called a runner class. Other times, they are called client programs. The main method is the point of entry for a program. That means that when the programmer runs the program, Java finds the main method first and executes it. You will not have to write main methods on the AP exam.
Notice that the Circle class does not contain a public static void main(String args) . The purpose of the Circle class is to define how to build and manipulate a Circle object; however, Circle objects are created and manipulated in a different class that contains a main method.
How to Make a New Object from a Class
When you want to make an object from a class, you have to call one of the class’s constructors. However, you may have more than one constructor, including the no-argument constructor or one or more parameterized constructors. The computer decides which constructor to call by looking at the parameter list in the declaration of each constructor. Whichever constructor matches the call to the constructor is used to create the object.
Write a runner class that instantiates three Circle objects. Make the first Circle object have a radius of 10, while the second and third Circles will get the default value. Manipulate the radii of the Circles and print their areas.
Every Object from the Same Class Is a Different Object
Every object that is constructed from a class has its own instance variables. Two different objects can have the same state , which means that their instance variables have the same values.
In this example, the CircleRunner class creates three different Circle objects called myCircle, hisCircle, and herCircle. Notice that the myCircle object has a radius of 10. This is because when the Circle object created it, the computer looked for the parameterized constructor and when it found it, assigned the 10 to the parameter rad. For the hisCircle and herCircle objects, the no-argument constructor was called and the instance variable, radius, was given the default value of 0.0.
Remember that myCircle, hisCircle, and herCircle all refer to different objects that were all created from the same Circle class and each object has its own radius. When each object calls the getArea method, it uses its own radius to compute the area.
The Dot Operator
The dot operator is used to call a method of an object. The name of the object’s reference variable is followed by a decimal point and then the name of the method.
Understanding the Keyword new When Constructing an Object
Beginning Java programmers often have a hard time understanding why the name of the class is used twice when creating an object, such as the Circle objects in the CircleRunner. Let’s analyze the following line of code to find out what’s really happening.
The first use of the word Circle is the data type of the variable. It’s similar to how we defined an int or a double variable. The variable myCircle is called a reference variable of type Circle. It’s similar to a primitive variable in that it holds a value, but it’s way different in the fact that it does not hold the Circle object itself. The value that myCircle holds is the memory address of the soon-to-be-created Circle object.
The second use of the word Circle(10) is a call to the parameterized constructor of the Circle class. The keyword new tells the computer, “Hey we are about ready to make a new object.” The computer looks for a constructor that has a single parameter that matches the data type of the 10. Once it finds this constructor, it gives the 10 to the parameter, rad. The code in the constructor assigns the instance variable, radius, the value of the parameter rad. Then, voilá! The radius of the Circle object is 10.
Finally, the computer looks for a place to store the Circle object in memory (RAM) and when it finds a location, it records the memory address. The construction of the Circle is now complete, and the address of the newly formed Circle object is assigned to the reference variable, myCircle.
Now, anytime you want to manipulate the object that is referenced by myCircle, such as give it a new radius, you are actually telling myCircle to go find the object that it is referencing (also called, pointing to ), and then set the radius for that object.
The Reference Variable
The reference variable does not hold the object itself. It holds the address of where the object is stored in RAM (random access memory).
The Reference Variable Versus the Actual Object
The following diagram is meant to help you visualize the relationship between object reference variables and the objects themselves in the computer’s memory. Note: The memory addresses are simulated and only meant to serve as an example of addresses in the computer’s memory.
Question 1: What happens after these two lines of code are executed?
Question 2: What do you suppose happens after this line of code is executed?
If you are following the diagram correctly, you will see that herCircle “takes on the value” of the address of the hisCircle reference variable. Now, herCircle contains the same address that hisCircle contains. This means that both reference variables contain the same address of the same object and are pointing to the same object. The word aliasing is used to describe the situation when two different object reference variables contain the same address of an object.
Look at the object that used to be referenced by herCircle. Nobody is pointing to it. It has been detached from the rest of the world and will be garbage collected by Java. This means that Java will delete it when it is good and ready.
The null Reference
When an object reference variable is created but not given the address of an object, it is considered to have a null reference . This simply means that it is supposed to know where an object lives, but it does not. Whenever you create an object reference variable and don’t assign it the address of an actual object, it has the value of null , which means that it has no value. You can also assign a reference variable the value of null to erase its memory of its former object.
The null Reference
A reference variable that does not contain the address of any object is called a null reference.
Question 3: What do you suppose happens when this statement is executed?
The reference variable hisCircle is now null; it has no value. This means that it does not contain the address of any object. The reference variable herCircle still holds the address of a Circle object and so it can access methods of that object.
- A class contains the blueprint, or design, from which individual objects are created.
- Classes tend to represent things that are nouns.
- A class declaration (or class definition) is the line of code that declares the class.
- By naming convention, class names begin with an uppercase letter and use camel case.
- The two access modifiers that are tested on the AP Computer Science A Exam are public and private.
- All classes should be declared public.
- A public class means that the class is visible to all classes everywhere.
- Instance variables (or fields) are properties that all objects from the same class possess. They are the attributes that help distinguish one object from another in the same class.
- All instance variables should be declared private.
- A class can have as many instance variables as is appropriate to describe all the attributes of an object from the class.
- By naming convention, all instance variables begin with a lowercase letter and use camel case.
- All primitive instance variables receive default values. The default value of an int is 0, the default value of a double is 0.0, and the default value for a boolean is false.
- The current values of all of the instance variables of an object determine the state of the object.
- The state of the object is changed whenever any of the instance variables are modified.
- Every class, by default, comes with a no-argument (or empty) constructor.
- Parameterized constructors should be created if there are values that should be assigned to the instance variables at the moment that an object is created.
- A class can have as many parameterized constructors as is relevant.
- The main reason to have a parameterized constructor is to assign values to the instance variables.
- Other code may be written in the constructor.
- A parameter is a variable that receives values and is declared in a parameter list of a method or constructor.
- The methods of a class describe the actions that an object can perform.
- Methods tend to represent things that are verbs.
- By naming convention, method names begin with a lowercase letter and use camel case.
- The name of a method should describe the purpose of the method.
- Methods should not be multi-purpose. They should have one goal.
- A method declaration describes pertinent information for the method such as the access modifier, the return type, the name of the method, and the parameter list.
- Methods that don’t return a value are called void methods.
- Methods that return a value of some data type are called return methods.
- Methods can return any data type.
- Return methods must include a reachable return statement.
- Methods that return the value of an instance variable are called accessor (or getter) methods.
- Methods that modify the value of an instance variable are called mutator (or modifier or setter) methods.
- The data type of all parameters must be defined in the parameter list.
- An object from a class is a virtual realization of the class.
- Objects store their own data.
- An instance of a class is the same thing as an object of a class.
- The word “instantiate” is used to describe the action of creating an object. Instantiating is the act of constructing a new object.
- The keyword new is used whenever you want to create an object.
- An object reference variable stores the memory address of where the actual object is stored. It can only reference one object.
- The reference variable does not store the object itself.
- Two reference variables are equal only if they refer to the exact same object.
- The word null means no value.
- A null reference describes a reference variable that does not contain an address of any object.
- You can create as many objects as you want from one class. Each is a different object that is stored in a different location in the computer’s memory.
1 . The relationship between a class and an object can be described as:
(A) The terms class and object mean the same thing.
(B) A class is a program, while an object is data.
(C) A class is the blueprint for an object and objects are instantiated from it.
(D) An object is the blueprint for a class and classes are instantiated from it.
(E) A class can be written by anyone, but Java provides all objects.
2 . Which of the following is a valid constructor declaration for the Cube class?
- public static Cube()
- public void Cube()
III. public Cube()
- public Cube(int side)
(A) I only
(B) II only
(C) III only
(D) I and II only
(E) III and IV only
Questions 3–7 refer to the following class.
3 . Which of the following could be used to instantiate a new Student object called sam ?
(A) Student sam = new Student();
(B) sam = new Student();
(C) Student sam = new Student("Sam Smith", 3.5);
(D) new Student sam = ("Sam Smith", 3.5);
(E) new Student(sam );
4 . Which of the following could be used in the StudentTester class to print the name associated with the Student object instantiated in problem 3?
5 . Which of the following is the correct way to write a method that changes the value of a Student object’s gpa variable?
6 . Consider the following code segment.
What is printed as a result of executing the code segment?
(D) Nothing will be printed. There will be a compile-time error.
(E) Nothing will be printed. There will be a run-time error.
7 . Free-Response Practice: Dream Vacation Class
Everyone fantasizes about taking a dream vacation.
Write a full DreamVacation class that contains the following:
- An instance variable for the name of the destination
- An instance variable for the cost of the vacation (dollars and cents)
- A no-argument constructor
- A parameterized constructor that takes in both the name of the vacation and the cost
- Accessor (getter) methods for both instance variables
- Modifier (setter) methods for both instance variables
Answers and Explanations
Bullets mark each step in the process of arriving at the correct solution.
1 . The answer is C.
- A class is a blueprint for constructing objects of the type described by the class definition.
2 . The answer is E.
- The general form of a constructor declaration is:
- Notice that there is no return type, not even void.
- In this example, the name of the class is Cube. III is a correct declaration for a no-argument constructor and IV is a correct declaration for a constructor with one parameter.
3 . The answer is C.
- The general form of an instantiation statement is:
- In this example, the type is Student and the variable name is sam.
- We have to look at the constructor code to see that the parameter list consists of a String followed by a double.
- The only answer that has the correct form with the parameters in the correct order is:
4 . The answer is B.
- We do not have direct access to the instance variables of an object, because they are private. We have to ask the object for the data we need with an accessor method. In this case, we need to call the getName method.
- We need to ask the specific object we are interested in for its name. The general syntax for doing that is:variableName.methodName();
- Placing the call in the print statement gives us:System.out.println(sam.getName());
5 . The answer is E.
- A modifier or setter method has to take a new value for the variable from the caller and assign that value to the variable. The new value is given to the method through the use of a parameter.
- A modifier method does not return anything. Why would it? The caller has given the value to the method. The method doesn’t have to give it back.
- So we need a void method that has one parameter. It has to change the value of gpa to the value of the parameter. Option E shows the only method that does that.
6 . The answer is C.
- The instantiation statements give us 2 objects: s1 and s2.
- s1 references (points to) a Student object with the state information: name = "Emma Garcia", gpa = 3.9
- s2 references (points to) a Student object with the state information: name = "Alice Garrett", gpa = 3.2
- When we execute the statement s2 = s1, s2 changes its reference. It now references the exact same object that s1 references, with the state information: name = "Emma Garcia", gpa = 3.9
- s2.setGpa(4.0); changes the gpa in the object that both s1 and s2 reference, so when s1.getGpa(); is executed, that’s the value it retrieves and that’s the value that is printed.
7 . On the AP exam, you are often asked to write an entire class, like you were in this question. Check your answer against our version below. The comments are to help you read our solution. Your solution does not need comments.
Make Variable Names Meaningful
It’s OK if you use different variable names from what we use in the solutions to the chapter questions. Just be sure that the names are meaningful.