5 Steps to a 5 AP Computer Science A 2017 (2016)

STEP 4

Review the Knowledge You Need to Score High

CONCEPT 7

Classes and Objects (Advanced Version)

IN THIS CONCEPT

Summary: This concept is the advanced continuation of Concept 2, Classes and Objects (Basic Version). In this concept you’ll find the explanations for topics such as passing parameters by reference, overloading methods and constructors, and the many uses of the word static. Full understanding of these concepts is key to scoring a 5 on the AP Computer Science A Exam.

Key Ideas

   Objects are passed by reference, while primitives are passed by value.

   Arrays are objects; therefore, they are passed by reference.

   Data encapsulation is a way of hiding user information.

   Overloaded constructors have the same name but different parameter lists.

   Overloaded methods have the same name but different parameter lists.

   Static variables are called class variables and are shared among all objects of the same class.

   Static final variables are called class constants and, once given a value, they cannot be changed during the running of the program.

   The keyword this is used to refer to the current object.

   Scope describes the region of the program in which a variable is known.

Parameters

Primitives Are Passed by Value

Values that are passed to a method or constructor are called actual parameters (or arguments ), while the variables in the parameter list of the method declaration are called formal parameters . When an actual parameter is of a primitive type, its value cannot be changed in the method because only the value of the variable is sent to the method.

Said another way, the formal parameter variable becomes a copy of the actual parameter. The method cannot alter the value of the actual parameter variable. The formal parameter variable only receives the value of the actual parameter. The method only has the ability to change the value of the formal parameter variable, not the value of the actual parameter.

Objects Are Passed by Reference

Objects are passed by reference. What does that mean?

Simple answer: It means that when an object is passed to a method, the method has the ability to change the state of the object.

Technical answer: When an actual parameter is an object, it is the object reference that is actually the parameter. This means that when the method receives the reference and stores it in a formal parameter variable, the method now has the ability to change the state of the object because it knows where the object lives . The formal parameter is now an alias of the actual parameter. Essentially, you have just given away the keys to the car.

Example

Demonstrate the difference between passing by reference and passing by value. The state of the object is changed in the method, while the state of the primitive variable is unchanged.

Arrays Are Passed by Reference

An array is an object, so this means that it will be passed by reference. If you pass an array as an actual parameter to a method or constructor, you are actually passing the reference to the array , which means that the method or constructor has the ability to change the elements in the array.

Example

Demonstrate that an array parameter can be used to modify the array. This is an example of destruction of persistent data , a one-point penalty on the free response. The array reference that was passed to the method allows the contents of the original array to be destroyed.

Destruction of Persistent Data

Recall that this is a one-point penalty on the free response. Don’t ever allow a method to change the state of the argument that is passed to it (unless you are asked to do so in the specifications).

Example

Correctly demonstrate how not to have destruction of persistent data. In this example, the method creates a temporary array and copies each of the values of the original array over to the temporary. Then, the temporary array is assigned values while leaving the original array untouched.

Comparing Against a null Reference

Recall that a nullPointerException error occurs if you attempt to perform a method on a reference variable that is null. How can you tell if a reference variable is null so you won’t get that error? The answer is to perform a null check. Compare the reference variable using the = = comparator or != comparator. Just don’t use the equals method to perform a null check. You’ll get a nullPointerException!

Example

Demonstrate how to perform a null check using the Circle class that was created in Concept 2. If the Circle reference is not null, then compute the area. If the Circle reference is null, then return -1 for the area.

Checking Against null

Never use the equals method to determine if an object reference is null. Only use == or != to check if an object reference variable is null.

Overloaded Constructors

It is possible to have more than one constructor in a class. Constructors are always declared using the name of the class, but their parameter lists can differ. If there are two or more constructors in a class, they are all called overloaded constructors . The computer decides which of the overloaded constructors is the correct one to use based on the parameter list.

Overloaded constructors have the same name; however, they must differ by one of these ways:

  • a different number of parameters
  • the same number of parameters but at least one is a different type
  • the same exact parameter types but in a different order

Example

Declare four constructors for a class called Student. The constructors have the same name as the class, but are different because their parameter lists differ.

Overloaded Methods

Methods that have the same name but different parameters lists are called overloaded methods . The computer decides which of the overloaded methods is the correct one to use based on the parameter list.

Overloaded methods must have the same name and may have a different return type; however, they must differ by one of these ways:

  • a different number of parameters
  • the same number of parameters but at least one is a different type
  • the same exact parameter types but in a different order

Example

Declare four overloaded methods. The methods should have the same name, but different parameter lists as described above.

Blast from the Past

Recall that the substring method from the String class is overloaded. There are two versions of the method, but they are different because their parameter lists are not identical.

static, static, static

static Variables (Class Variables)

There are times when a class wants to have a variable that is shared by all the objects that come from the class. If any one of the objects changes the value of this variable, then the change is reflected in the state of every object from the class. The variable is declared and assigned a value as though it were an instance variable; however, it uses the keyword static in its declaration. Static variables are also called class variables and like all instance variables, are declared private.

Example

Suppose you are hired by Starbucks to keep track of the total number of coffees that they serve. You’ve already decided to have a class called StarbucksStore, but how can you keep track of the total number of coffees served by all of the stores? One solution is to make a static variable, called totalCoffeesServed. Then, create a method to increment this class variable every time a coffee is served.

static Methods

If a method is labeled static, it can only call other static methods and can only use static variables. The most common place to use a static method is in a runner class. The main method is static and so it can only call other static methods. The main method is static because there aren’t any objects to initiate a call to run the program.

Example

Demonstrate how the main method can call static methods.

static final Variables (Class Constants)

There are times when a class wants to have a constant that is used by all the objects of the class. As the name constant suggests, it cannot be reassigned a different value at any other place in the program. In fact, a compile-time error will occur if you try to give the constant a different value. Class constants are declared using the keywords static and final in their declaration and use all uppercase letters (and underscores, if necessary). These static final variables are also called class constants .

Example

As the programmer assigned to the Starbucks project, you decide to make a variable that holds the logo for all the stores. You choose to make this variable a constant because every store shares the logo, and none of them should be allowed to change the logo. Once the program starts, the logo cannot be changed.

Data Encapsulation

Information Hiding

Protecting information by restricting its access is important in software development. Since classes are public, all the objects from the class are public. The way that we hide information or encapsulate data in Java is to use private access modifiers.

Encapsulated Data

It is expected on the AP Computer Science A Exam that all instance variables of a class are declared private. The only way to gain access to them is to use the accessor or mutator methods provided by the class.

What Happens if I Declare an Instance Variable public ?

Let’s suppose you just want to find out what happens if you declare an instance variable public. The result is that you can use the dot operator to access the instance variables.

Example

Declare the radius instance variable from the Circle class as public. Notice that the object has now allowed access to the public variable by anyone using the dot operator. Using the dot operator on a private variable produces a compile-time error.

The Integer Class and Its public Fields

Remember how we accessed the largest and smallest Integer? We used the dot operator to just get the value. That’s because MAX_VALUE and MIN_VALUE are public constant fields of the Integer class. You don’t use an accessor method to get them.

Scope

The scope of a variable refers to the region of the program in which the variable is known. Attempting to use a variable outside of its scope produces a compile-time error.

Different types of variables have different scopes.

  • The scope of alocal variable is within the nearest pair of curly braces that encloses it.
  • The scope of aparameter is the method or constructor in which it is declared.
  • The scope of aninstance variable is the class in which it is defined.

Documentation

Javadoc

Javadoc is a tool that generates an HTML-formatted document that summarizes a class (including its constructors, instance variables, methods, etc.) in a readable format. Among programmers, this document itself is often referred to as a Javadoc. The summary is called the API (application program interface) for that set of classes and is extremely useful for programmers.

Javadoc Tags

Similar to a hashtag, the @param is a tag that is used in Javadoc comments. When a programmer uses an @param tag, they state the name of the parameter and provide a brief description of it. Javadoc tags are automatically detected by Javadoc and appear in the API.

The @return is also a Javadoc tag. It is only used in return methods, and the programmer identifies the name of the variable being returned and a brief description of it.

Precondition and Postcondition

You know what happens when you assume, right? Well, a precondition states what you are allowed to assume about a parameter. It’s a statement in the documentation comment before a constructor or method signature that describes the expectations of the parameter sent to the method. On the AP Computer Science A Exam, reading the preconditions can help you understand the nature of the parameters. A postcondition is what is expected of the method after it is executed.

Documentation Comments on the AP Computer Science A Exam

You won’t have to write any Javadoc comments on the AP exam. You just need to know how to read them.

Example

This is the same Circle class that was created in Concept 2; however, it now includes the Javadoc tags and precondition/postcondition statements as they may appear on the AP Computer Science A Exam. It also includes an improved way to calculate the area using the Math class.

The Keyword this

The keyword this is a reference to the current object, or rather, the object whose method or constructor is being called. It is also referred to as the implicit parameter.

Example 1

Pass the implicit parameter this to a different method in a class. This usage may be tested on the exam.

Example 2

A common place to use the keyword this is when the instance variables have the same name as the parameters in a constructor. The keyword this is used on the left side of the assignment statements to assign the instance variables the values of the parameters. The left side is the instance variable; the right side is the parameter variable. Using this here says, “Hey, I understand that we have the same name, so these are my instance variables and not the parameters.” This usage of the keyword this is not tested on the exam.

IllegalArgumentException

If you pass an argument to a method and the value of the argument does not meet certain criteria required by the method, an IllegalArgumentException error may be thrown during run-time. Programmers may also choose to write a method that terminates with an IllegalArgumentException if it does not receive the expected input.

 Rapid Review

Passing Parameters by Value

  • The parameter variables that are passed to a method or constructor are called actual parameters (or arguments).
  • The parameter variables that receive the values in a method or constructor are called formal parameters.
  • Passing by value means that only the value of the variable is passed.
  • Primitive variables are passed by value.
  • It is impossible to change the value of actual parameters that are passed by value.

Passing Parameters by Reference

  • Passing by reference means that the address of where the object is stored is passed to the method or constructor.
  • Objects are passed by reference (including arrays).
  • The state of the object can be modified when it is passed by reference.
  • It is possible to change the value of actual parameters that are passed by reference.

Overloaded

  • Overloaded constructors may have (1) a different number of parameters, (2) the same number of parameters but of a different type, or (3) the same exact parameter types but in a different order.
  • Overloaded methods have the same name; however, their method parameter lists are different in some way.
  • Overloaded methods may have (1) a different number of parameters, (2) the same number of parameters but of a different type, (3) the same exact parameter types but in a different order.

static

  • Static variables are also known as class variables.
  • A class variable is a variable that is shared by all instances of a class.
  • Changes made to a class variable by any object from the class are reflected in the state of each object for all objects from the class.
  • Static final variables are also called class constants.
  • Class constants are declared using both the keywordsstatic and final .
  • Constants, by naming convention, use uppercase letters and underscores.
  • Constants cannot be modified during run-time.
  • If a method is declared static, it can only call other static methods and can reference static variables.

Scope

  • The scope of a variable refers to the area of the program in which it is known.
  • The scope of a local variable is in the block of code in which it is defined.
  • The scope of an instance variable is the class in which it is defined.
  • The scope of a parameter is the method or constructor in which it is defined.

Documentation

  • Documentation tags are used by Javadocs.
  • The @param tag is used to describe a parameter.
  • The @return tag is used to describe what is being returned by a method.
  • A precondition describes what can be expected of the values that the parameters receive.
  • A postcondition describes the end result criteria for a method.

Miscellaneous

  • Data encapsulation is the act of hiding the values of the instance variables from other classes.
  • Declaring instance variables as private encapsulates them.
  • Declaring instance variables as public allows instant access to them using the dot operator.
  • Use the keywordthis when you want to refer to the object itself.
  • An IllegalArgumentException error occurs when a parameter that is passed to a method fails to meet criteria set up by the programmer.

 Review Questions

Basic Level

Questions 1–2 refer to the following information.

Consider the following method:

  1. The following code segment appears in another method in the same class.

What is printed as a result of executing the code segment?

(A)   2

(B)   9

(C)   23

(D)   40

(E)   49

  1. The following code segment appears in another method in the same class.

What is printed as a result of executing the code segment?

(A)   40 49 40

(B)   9 2 40

(C)   40 49 49

(D)   Run-time error: a and b cannot contain two values at once.

(E)   Compile-time error. Duplicate variable.

  1. The following method performs the same calculation as the method in questions 1 and 2, but now the int values are contained in an array.

The following code segment appears in another method in the same class.

What is printed as a result of executing the code segment?

(A)   40 49 40

(B)   9 2 40

(C)   40 49 2

(D)   9 2 49

(E)   Nothing will be printed. Program will terminate with an error.

  1. Consider the following calculation of the area of a circle.

Math.PI can best be describes as:

(A)   A method in the Math class.

(B)   A method in the class containing the given line of code.

(C)   A public static final double in the Math class.

(D)   A private static final double in the Math class.

(E)   A private static final double in the class containing the given line of code.

  1. A programmer is designing aBankAccount class. In addition to the usual information needed for a bank account, she would like to have a variable that counts how many BankAccount objects have been instantiated. She asks you how to do this. You tell her:

(A)   It cannot be done, since each object has its own variable space.

(B)   She should use a class constant.

(C)   She should call a mutator method to change the numAccounts variable held in each object.

(D)   She should create a static variable and increment it in the constructor as each object is created.

(E)   Java automatically keeps a tally. She should reference the variable maintained by Java.

  1. Having multiple methods in a class with the same name but with a different number or different types of parameters is called:

(A)   abstraction

(B)   method overloading

(C)   encapsulation

(D)   method visibility

(E)   parameterization

Advanced Level

  1. Consider the following method.

Which statement about this method is true?

(A)   mystery returns the smallest of the three integers a , b , and c .

(B)   mystery always returns the value of a .

(C)   mystery always returns both values a and c .

(D)   mystery sometimes returns all three values a , b , and c .

(E)   mystery will not compile, because the return statement appears to be unreachable under some conditions.

  1. The method from the problem above is re-written as shown.

Now, which statement about the method is true?

(A)   mystery2 returns the smallest of the three integers a , b , and c .

(B)   mystery2 always returns the value of c .

(C)   mystery2 returns either the values of both a and c or both b and c .

(D)   mystery2 sometimes returns all three values a , b , and c .

(E)   mystery2 will not compile, because the return statement appears to be unreachable under some conditions.

Questions 9–10 refer to the following information.

Consider the following class declaration.

  1. The following code segment appears in the main method of another class.

What is printed as a result of executing the code segment?

(A)   30

(B)   15

(C)   7.75

(D)   7.5

(E)   7

  1. The following code segment appears in the main method of another class.

Which of the following statements should be used to replace /* missing condition */ so that the code segment will not terminate with a NullPointerException ?

(A)   if (acArray[i] != null)

(B)   if (acArray.get(i) != null)

(C)   if (acArray.getData() != null)

(D)   if (acArray.getData().equals("two") || acArray.getData().equals("three"))

(E)   Since not all of acArray’s entries contain an AnotherClass object, there is no way to loop through the array without a NullPointerException .

  1. Consider the following method declaration.

Which of these method declarations would correctly overload the given method?

  1. public double workaround(int a, double b)
  2. public int workaround(double b, int a)

III.   public int workaround(String s, double b)

  1. public double workaround(int a, double b, String s)
  2. public int workaround(int b, double a)

(A)   I only

(B)   IV only

(C)   II and III only

(D)   II, III, and IV only

(E)   All of the above

  1. Free-Response Practice: TheHeight Class

The purpose of the Height class is to hold a measurement in feet and inches, facilitate additions to that measurement, and keep the measurement in simplest form (inches < 12). A Height object can be instantiated with a measurement in feet and inches, or in total inches.

Write the entire Height class that includes the following:

  • Instance variablesint feet for the number of feet and int inches for the number of inches. These instance variables must be updated anytime they are changed so that they hold values in simplest form. That is, inches must always be less than 12 (see method described in part C below).
  • Two constructors, one with two parameters representing feet and inches, and one with a single parameter representing inches. The parameters do not necessarily represent the measurement simplest form.
  • A method calledsimplify() that recalculates the number of feet and inches, if necessary, so that the number of inches is less than 12.
  • Anadd(int inches) method that takes the number of inches to add and updates the appropriate instance variables.
  • Anadd(Height ht) method that takes a parameter that is a Height object and adds that object’s inches and feet to this object’s instance variables, updating if necessary.
  • Accessor (getter) methods for the instance variablesinches and feet .

 Answers and Explanations

Bullets mark each step in the process of arriving at the correct solution.

  1. The answer is D.
  • When the method call calculate(var, count) is executed, the arguments 9 and 2 are passed by value. That is, their values are copied into the parameters a and b, so a = 9 and b = 2 at the beginning of the method.
  • a = 9 – 2 = 7
  • int c = 2
  • b = 7 * 7 = 49
  • a = 49 – (7 + 2) = 40 and that is what will be returned.
  1. The answer is B.
  • When the method call calculate(a, b) is executed, the arguments 9 and 2 are passed by value, that is their values are copied into the parameters a and b. The parameters a and b are completely different variables from the a and b in the calling method and any changes made to a and b inside the method do not affect a and b in the calling method in any way.
  • We know from problem #1 that calculate(9, 2) will return 40.
  • 9 2 40 will be printed.
  1. The answer is A.
  • This time, when the method call calculate(myArr) is executed, the argument myArr is passed by reference. Thereference to myArr is copied into the parameter arr, so now arr and myArr both point to the same object. Any changes made to arr in the method are also made to myArr, since it references the same object as arr. When the method returns, the variable arr no longer exists, but the changes made using its name can still be seen by accessing the array with the variable myArr.
  • Refer to the explanation for problem #1 to see the calculations (only the names have changed).
  • 40 49 40 will be printed.
  1. The answer is C.
  • All instance variables in the classes we write must be declared private. In fact, the AP exam readers may deduct points if you do not declare your variables private. However, some built-in Java classes provide us with useful constants by making their fields public.
  • We access these fields by using the name of the class followed by a dot, followed by the name of the field. We can tell that it is a constant because its name is written entirely in capital letters. Some other public constants that we use are Integer.MAX_VALUE and Integer.MIN_VALUE.
  • Note that we can tell this is not a method call, because the name is not followed by (). The Math.pow(radius, 2) is a method call to a static method of the Math class.
  1. The answer is D.
  • Option A is incorrect. It correctly states that each object has its own variable space, and each object’s variables will be different. However, it is not correct about it being impossible.
  • Option B is incorrect. It says to use a constant, which doesn’t make sense because she wants to be able to update its value as objects are created.
  • Option C is incorrect. There is no one mutator method call that will access the instance variables of each object of the class.
  • Option D is correct. A static variable or class variable is a variable held by the class and accessible to every object of the class.
  • Option E is simply not true.
  1. The answer is B.
  • Method overloading allows us to use the same method name with different parameters.
  1. The answer is E.
  • The intent of the mystery method is to find and return the smallest of the three integers. We know that all possible conditions are covered by the if statements and one of them has to be true, but the compiler does not know that. The compiler just sees that all of the return statements are in if clauses, and so it thinks that if all the conditions are false, the method will not return a value. The compiler generates an error message telling us that the method must return a value.
  1. The answer is A.
  • The first time a return statement is reached, the method returns to the caller. No further code in the method will be executed, so no further returns will be made.
  1. The answer is E.
  • There are a lot of calls here, but only two that will affect the value of val, since the only time val is changed is in the constructor.
  • It’s important to notice that val is a static variable. That means that the class maintains one copy of the variable, rather than the objects each having their own copy. Since there is only one shared copy, changes made to val by any object will be seen by all objects.
  • The first time the constructor is called is when the word “object” is instantiated. val = 31 when the constructor is called and this call to the constructor changes its value to 15 (integer division).
  • The second time the constructor is called is when the sentence object is instantiated. This time val = 15 when the constructor is called and this call to the constructor changes its value to 7 (integer division).
  1. The answer is A.
  • acArray is an array of objects. Initially, all the entries in the array are null. That is, they do not reference anything. If a program tries to use one of these entries as if it were an object, the program will terminate with a NullPointerException.
  • To avoid the NullPointerException, we must not attempt to use a null entry as if it contained a reference to an object.
  • Option B is incorrect. It uses ArrayList syntax, not array syntax, so it will not even compile.
  • Options C and D are incorrect. They attempt to call getData() on a null entry and so will terminate with a NullPointerException.
  • Option A is correct. It checks to see whether the array entry is null before allowing the System.out.println statement to treat it as an object.
  1. The answer is D.
  • Options I and IV are incorrect. An overloaded method must have a different parameter list so that the compiler knows which version to use.
  • Options II, III, and IV are valid declarations for overloaded methods. They can all be distinguished by their parameter lists.
  1. TheHeight Class

Note: There are many ways to write the simplify method. If you aren’t sure if yours works, type it into your IDE. Here’s one alternate solution:







All materials on the site are licensed Creative Commons Attribution-Sharealike 3.0 Unported CC BY-SA 3.0 & GNU Free Documentation License (GFDL)

If you are the copyright holder of any material contained on our site and intend to remove it, please contact our site administrator for approval.

© 2016-2024 All site design rights belong to S.Y.A.