Chapter 7 Flashcards
Name all components in the following method declaration:
public final void nap(int minutes) throws InterruptedException {}
- Access modifier
- Optional specifier
- Return type
- Method name
- Parantheses
- Parameter(s)
- Exception
- Method body
What are the method name and parameter list also called?
Method signature
What are all access modifiers?
- Private
- Default (Package-private)
- Protected
- Public
What are all optional specifiers?
- static
- abstract (when a method body is not provided)
- final (used when a method is not allowed to be overridden)
- synchronized (used with multithreaded code)
- native (not on exam)
- strictfp (not on exam)
What are the rules for method names?
Same as variable names
- Can contain letters, numbers, underscore and $
- Cannot start with a number
- Cannot be a reserved word
- Single underscore is not allowed
What is the difference between an array and varargs?
Varargs have one additional rule in that it must be the last element in a method’s parameter list.
What is the scope of the private access modifier?
Only accessible within the same class
What is the scope of the default access modifier?
Private plus other classes in the same package
What is the scope of the protected access modifier?
Default access plus child classes
What is the scope of the public access modifier?
Protected access plus other packages
What does the following code print?
public class Koala { public static int count = 0; }
class TestKoala { public static void main(String[] args) { Koala k = new Koala(); System.out.println(k.count); k = null; System.out.println(k.count); } }
0 twice
page 267
What does it mean when we say Java is a “pass-by-value” language?
This means that a copy of the variable is made and the method receives that copy. Assignments made in the method do not affect the caller.
What is printed in the following code?
public static void main(String[] args) { String name = "Willie"; speak(name); System.out.println(name); }
public static void speak(String name) {
name = “Wulm”;
}
“Willie”
The variable assignment is only to the method parameter and doesn’t affect the caller.
What are the rules for method overloading?
- The method must have an equal name
- The method must have different parameters (different type(s) or more parameters)
- Everything else can vary
Can I overload a method with an array parameter with a method with a varargs parameter?
No. Java treats varargs as if they were an array. You can pass an array to one of the methods and Java would not know which method to call.