Chapter 7 Methods and Encapsulation Flashcards
Images
https://github.com/zero14c/OCP-Notes/blob/2cb97c8c72f0031567538aaedef9cfe80971a0a9/images/Chapter%207%20images.md
Tables
https://github.com/zero14c/OCP-Notes/blob/061afc7e53406ab3361d605b2f7eceae1f66c708/1Z0-815/Chapter%207%20Methods%20and%20Encapsulation/Chapter%207%20tables.md
Methods and Encapsulation
Method declaration
This is called a method declaration, which specifies all the information needed to call the method. There are a lot of parts, and we’ll cover each one in more detail. Two of the parts—the method name and parameter list—are called the method signature.
Method declaration
https://github.com/zero14c/OCP-Notes/blob/2cb97c8c72f0031567538aaedef9cfe80971a0a9/images/Chapter%207%20images.md
Parts of a method declaration
public final void nap(int minutes) throws InterruptedException { // take a nap }
Access modifier
, public, optionalOptional specifier
, final, optionalReturn type
, void, requiredMethod name
, nap, requiredParameter list
, (int minutes), required, but can be empty parenthesesOptional exception list
, throws InterruptedException, optionalMethod body
,{// take a nap}
, required for concrete method but can be empty braces, ommited for abstract method.
How to call method?
~~~
public final void nap(int minutes) throws InterruptedException {
// take a nap
}
~~~
To call this method, just type its name, followed by a single int value in parentheses:nap(10);
ACCESS MODIFIERS
Java offers four choices of access modifier:
1. private The private modifier means the method can be called *only*
from within the same class.
2. Default (Package-Private) Access With default access, the method can be called *only*
from classes in the same package. This one is tricky because there is no keyword for default access. You simply omit the access modifier.
3. protected The protected modifier means the method can be called only from classes in the same package or subclasses. You’ll learn about subclasses in Chapter 8, “Class Design.”
4. public The public modifier means the method can be called from any class.
Note:
There’s a default keyword in Java. You saw it in the switch statement in Chapter 4, “Making Decisions,” and you’ll see it again in the Chapter 9, “Advanced Class Design,” when I discuss interfaces. It’s not used for access control.
public void walk1() {} default void walk2() {} // DOES NOT COMPILE void public walk3() {} // DOES NOT COMPILE void walk4() {}
The walk1() method is a valid declaration with public access.
The walk4() method is a valid declaration with default access.
The walk2() method doesn’t compile because default
is not a valid access modifier.
The walk3() method doesn’t compile because the access modifier is specified after the return type.
OPTIONAL SPECIFIERS
can have multiple optional specifiers in the same method (although not all combinations are legal).
When this happens, you can specify them in any order.
And since these specifiers are optional, you are allowed to not have any of them at all. This means you can have zero
or more
specifiers in a method declaration.
OPTIONAL SPECIFIERS
- static The static modifier is used for class methods and will be covered later in this chapter.
- abstract The abstract modifier is used when a method body is not provided. It will be covered in Chapter 9.
- final The final modifier is used when a method is not allowed to be overridden by a subclass. It will also be covered in Chapter 8.
- synchronized The synchronized modifier is used with multithreaded code. It is on the 1Z0-816 exam, but not the 1Z0-815 exam.
- native The native modifier is used when interacting with code written in another language such as** C++**. It is not on either OCP 11 exam.
- strictfp The strictfp modifier is used for making floating-point calculations portable. It is not on either OCP 11 exam.
public void walk1() {} public final void walk2() {} public static final void walk3() {} public final static void walk4() {} public modifier void walk5() {} // DOES NOT COMPILE public void final walk6() {} // DOES NOT COMPILE final public void walk7() {}
- The walk1() method is a valid declaration with no optional specifier. This is okay—it is optional after all.
- The walk2() method is a valid declaration, with final as the optional specifier.
- The walk3() and walk4() methods are valid declarations with both final and static as optional specifiers. The order of these two keywords doesn’t matter.
- The walk5() method doesn’t compile because
modifier
is not a valid optional specifier. - The walk6() method doesn’t compile because the optional specifier is after the
return type
. - The walk7() method does compile. Java allows the optional specifiers to appear before the access modifier. This is a weird case and not one you need to know for the exam. We are mentioning it so you don’t get confused when practicing.
RETURN TYPE
The return type
might be an actual Java type such as String or int. If there is no return type
, the void
keyword is used.
Note:
Remember that a method must have a return type. If no value is returned, the return type is void
. You cannot omit the return type.
return statement is required in the method body if return type is not void.
When checking return types, you also have to look inside the method body.
Methods with a return type other than void
are **required to have a return statement inside the method body. **
This return statement must include the primitive or object to be returned.
Methods that have a return type of void are permitted to have a return statement with no value returned or omit the return statement entirely.
public void walk1() {} public void walk2() { return; } public String walk3() { return ""; } public String walk4() {} // DOES NOT COMPILE public walk5() {} // DOES NOT COMPILE public String int walk6() { } // DOES NOT COMPILE String walk7(int a) { if (a == 4) return ""; } // DOES NOT COMPILE
- Since the return type of the walk1() method is void, the **return statement is optional. **
- The walk2() method shows the optional return statement that correctly doesn’t return anything.
- The walk3() method is a valid declaration with a String return type and a return statement that returns a String.
- The walk4() method doesn’t compile because the return statement is missing.
- The walk5() method doesn’t compile because the return type is missing.
- The walk6() method doesn’t compile because it attempts to use two return types. You get **only one return type. **
- The walk7() method is a little tricky. There is a return statement, but it doesn’t always get run. If a is 6, the return statement doesn’t get executed. Since the String always needs to be returned, the compiler complains.
int integer() { return 9; } int longMethod() { return 9L; // DOES NOT COMPILE }
When returning a value, it needs to be assignable to the return type.
int integerExpanded() { int temp = 9; return temp; } int longExpanded() { int temp = 9L; // DOES NOT COMPILE return temp; }
This shows more clearly why you can’t return a long primitive in a method that returns an int. You can’t stuff that long into an int variable, so you can’t return it directly either.
METHOD NAME
Method names follow the same rules as we practiced with variable names
An identifier may only contain letters, numbers, $, or _
.
Also, the first character is not allowed to be a number, and reserved words are not allowed.
Finally, the single underscore character is not allowed.
By convention, methods begin with a lowercase
letter but are not required to.
public void walk1() {} public void 2walk() {} // DOES NOT COMPILE public walk3 void() {} // DOES NOT COMPILE public void Walk_$() {} public _() {} // DOES NOT COMPILE public void() {} // DOES NOT COMPILE
- The walk1() method is a valid declaration with a traditional name.
- The 2walk() method doesn’t compile because identifiers are not allowed to begin with numbers.
- The walk3() method doesn’t compile because the method name is before the return type.
- The Walk_$() method is a valid declaration. While it certainly isn’t good practice to start a method name with a capital letter and end with punctuation, it is legal.
- The _ method is not allowed since it consists of a single underscore.
- The final line of code doesn’t compile because the method name is missing.
PARAMETER LIST
Although the parameter list is required, it doesn’t have to contain any parameters. This means you can just have an empty pair of parentheses after the method name as follows:void nap(){}
If you do have multiple parameters, you separate them with a comma.
public void walk1() {} public void walk2 {} // DOES NOT COMPILE public void walk3(int a) {} public void walk4(int a; int b) {} // DOES NOT COMPILE public void walk5(int a, int b) {}
- The walk1() method is a valid declaration without any parameters.
- The walk2() method doesn’t compile because it is missing the parentheses around the parameter list.
- The walk3() method is a valid declaration with one parameter.
- The walk4() method doesn’t compile because the parameters are separated by a semicolon rather than a comma. Semicolons are for separating statements, not for parameter lists.
- The walk5() method is a valid declaration with two parameters.
OPTIONAL EXCEPTION LIST
In Java, code can indicate that something went wrong by throwing an exception.
Exception list is optional.
For example, InterruptedException is a type of Exception. You can list as many types of exceptions as you want in this clause separated by commas. Here’s an example:
~~~
public void zeroExceptions() {}
public void oneException() throws IllegalArgumentException {}
public void twoExceptions() throws IllegalArgumentException, InterruptedException {}
~~~
You might be wondering what methods do with these exceptions. The calling method can throw the same exceptions or handle them.
METHOD BODY
The final part of a method declaration is the method body (except for abstract methods and interfaces).
A method body is simply a code block. It has braces that contain zero or more Java statements.
public void walk1() {} public void walk2() // DOES NOT COMPILE public void walk3(int a) { int name = 5; }
- The walk1() method is a valid declaration with an empty method body.
- The walk2() method doesn’t compile because it is missing the braces around the empty method body.
- The walk3() method is a valid declaration with one statement in the method body.
Working with Varargs
a method may use a varargs parameter (variable argument) as if it is an array. It is a little different than an array, though.
A varargs parameter must be the last element in a method’s parameter list.
This means you are allowed to have only one varargs parameter per method.