JAVA OCA ‎1Z0-808 Chapter 4 - Methods and Encapsulation

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

Since the return type of walk1() is void, the return statement is optional. walk2() shows the optional return statement that correctly doesn't return anything. walk3() is a valid method with a String return type and a return statement that returns a String. walk4() doesn't compile because the return statement is missing. walk5() doesn't compile because the return type is missing. walk6() 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.

Do there compile? public void walk1() { } public void walk2() { return; } public String walk3() { return ""; } public String walk4() { } public walk5() { } String walk6(int a) { if (a == 4) return ""; }

walk1() is a valid method declaration with a traditional name. 2walk() doesn't compile because identifi ers are not allowed to begin with numbers. walk3() doesn't compile because the method name is before the return type. Walk_$() is a valid method 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 fi nal line of code doesn't compile because the method name is missing.

Do these compile? public void walk1() { } public void 2walk() { } public walk3 void() { } public void Walk_$() { } public void()

walk1() is a valid method declaration without any parameters. walk2() doesn't compile because it is missing the parentheses around the parameter list. walk3() is a valid method declaration with one parameter. walk4() doesn't compile because the parameters are separated by a semicolon rather than a comma. Semicolons are for separating statements, not parameter lists. walk5() is a valid method declaration with two parameters

Do these compile? public void walk1() { } public void walk2 { } public void walk3(int a) { } public void walk4(int a; int b) { } public void walk5(int a, int b) { }

D, G. Option D passes the initial parameter plus two more to turn into a vararg array of size 2. Option G passes the initial parameter plus an array of size 2. Option A does not compile because it does not pass the initial parameter. Options E and F do not compile because they do not declare an array properly. It should be new boolean[] {true}. Option B creates a vararg array of size 0 and option C creates a vararg array of size 1.

Given the following method, which of the method calls return 2? (Choose all that apply) public int howMany(boolean b, boolean... b2) { return b2.length; } A. howMany(); B. howMany(true); C. howMany(true, true); D. howMany(true, true, true); E. howMany(true, {true}); F. howMany(true, {true, true}); G. howMany(true, new boolean[2]);

F Encapsulation requires using methods to get and set instance variables so other classes are not directly using them. Instance variables must be private for this to work. Immutability takes this a step further, allowing only getters, so the instance variables do not change state.

Immutability allows setters.

F Encapsulation requires using methods to get and set instance variables so other classes are not directly using them. Instance variables must be private for this to work. Immutability takes this a step further, allowing only getters, so the instance variables do not change state.

Immutability uses package private instance variables.

T Encapsulation requires using methods to get and set instance variables so other classes are not directly using them. Instance variables must be private for this to work. Immutability takes this a step further, allowing only getters, so the instance variables do not change state.

Immutability uses private instance variables.

Hopefully, you answered 5. There is only one count variable since it is static. It is set to 4, then 6, and finally winds up as 5. All the Koala variables are just distractions.

Koala.count = 4; Koala koala1 = new Koala(); Koala koala2 = new Koala(); koala1.count = 6; koala2.count = 5; System.out.println(Koala.count);

a -> a.canHop() Let's look at what is going on here. it has three parts: ■ Specify a single parameter with the name a ■ The arrow operator to separate the parameter and body ■ A body that calls a single method and returns the result of that method

Lambda syntax omitting optional parts

(Animal a) -> { return a.canHop(); } ■ Specify a single parameter with the name a and stating the type is Animal ■ The arrow operator to separate the parameter and body ■ A body that has one or more lines of code, including a semicolon and a return statement

Lambda syntax, including optional parts

Exact match by type Larger primitive type Autoboxed type Varargs

Order Java uses to choose the right overloaded method

1. If there is a superclass, initialize it first (we'll cover this rule in the next chapter. For now, just say "no superclass" and go on to the next rule.) 2. Static variable declarations and static initializers in the order they appear in the file. 3. Instance variable declarations and instance initializers in the order they appear in the file. 4. The constructor.

Order of Initialization

■ A member is used without referring to a variable. This is the case on lines 5 and 6. In this case, we are taking advantage of inheritance and protected access is allowed. ■ A member is used through a variable. This is the case on lines 10, 11, 15, and 16. In this case, the rules for the reference type of the variable are what matter. If it is a subclass, protected access is allowed. This works for references to the same class or a subclass

Protected class rules scenarios

T

T/F .Java allows calling a static method through an instance variable

F

T/F A public class that has private fields and package private methods is not visible to classes outside the package.

T Encapsulation requires using methods to get and set instance variables so other classes are not directly using them. Instance variables must be private for this to work. Immutability takes this a step further, allowing only getters, so the instance variables do not change state.

T/F Encapsulation allows setters.

F Encapsulation requires using methods to get and set instance variables so other classes are not directly using them. Instance variables must be private for this to work. Immutability takes this a step further, allowing only getters, so the instance variables do not change state.

T/F Encapsulation uses package private instance variables.

T Encapsulation requires using methods to get and set instance variables so other classes are not directly using them. Instance variables must be private for this to work. Immutability takes this a step further, allowing only getters, so the instance variables do not change state.

T/F Encapsulation uses private instance variables.

F

T/F Package private access is more lenient than protected access.

F

T/F Static methods are allowed to call instance methods.

F The default constructor is only written by the compiler if no user-defined constructors were provided. this() can only be called from a constructor in the same class. Since there can be no user-defined constructors in the class if a default constructor was created, it is impossible for option F to be true.

T/F You can call the default constructor written by the compiler using this().

T

T/F You can call the default constructor written by the compiler using this().

F, package private access applies to the whole package.

T/F You can use access modifiers so only some of the classes in a package see a particular package private class.

T. This is the common implementation for encapsulation by setting all fields to be private and all methods to be public.

T/F You can use access modifiers to allow read access to all methods, but not any instance variables.

F

T/F You can use access modifiers to restrict read access to all classes that begin with the word Test.

F

T/F You must include a default constructor in the code if the compiler does not include one.

T

T/F static final variables must be set exactly once, and it must be in the declaration line or in a static initialization block.

F Since the main() method is in the same class, it can call private methods in the class. this() may only be called as the first line of a constructor. this.variableName can be called from any instance method to refer to an instance variable. It cannot be called from a static method because there is no instance of the class to refer to.

T/F this() can be called from anywhere in a constructor.

T

T/F this.variableName can be called from any instance method in the class.

F

T/F this.variableName can be called from any static method in the class

We are telling Java that we only care about Animals that can hop.

What does this expression mean? print(animals, a -> a.canHop());

C, E. Option A is incorrect because the property is of type boolean and getters must begin with is for booleans. Options B and D are incorrect because they don't follow the naming convention of beginning with get/is/set. Options C and E follow normal getter and setter conventions.

Which are methods using JavaBeans naming conventions for accessors and mutators? (Choose all that apply) A. public boolean getCanSwim() { return canSwim;} B. public boolean canSwim() { return numberWings;} C. public int getNumWings() { return numberWings;} D. public int numWings() { return numberWings;} E. public void setCanSwim(boolean b) { canSwim = b;}

Trick question! Remember that Java treats varargs as if they were an array. This means that the method signature is the same for both methods. Since we are not allowed to overload methods with the same parameter list, this code doesn't compile. Even though the code doesn't look the same, it compiles to the same parameter list.

Which method do you think is called if we pass an int[]? public void fly(int[] lengths) { } public void fly(int... lengths) { }

B, C. void is a return type. Only the access modifier or optional specifiers are allowed before the return type. Option C is correct, creating a method with private access. Option B is correct, creating a method with default access and the optional specifier final. Since default access does not require a modifier, we get to jump right to final. Option A is incorrect because default access omits the access modifier rather than specifying default. Option D is incorrect because Java is case sensitive. It would have been correct if public were the choice. Option E is incorrect because the method already has a void return type. Option F is incorrect because labels are not allowed for methods

Which of the following can fill in the blank in this code to make it compile? (Choose all that apply) public class Ant { _____ void method() { } } A. default B. final C. private D. Public E. String F. zzz:

A, D. Options A and D are correct because the optional specifiers are allowed in any order. Options B and C are incorrect because they each have two return types. Options E and F are incorrect because the return type is before the optional specifier and access modifier, respectively.

Which of the following compile? (Choose all that apply) A. final static void method4() { } B. public final int void method() { } C. private void int method() { } D. static final void method3() { } E. void final method() {} F. void public method() { }

A, B, G. Options A and B are correct because the single vararg parameter is the last parameter declared. Option G is correct because it doesn't use any vararg parameters at all. Options C and F are incorrect because the vararg parameter is not last. Option D is incorrect because two vararg parameters are not allowed in the same method. Option E is incorrect because the ... for a vararg must be after the type, not before it.

Which of the following compile? (Choose all that apply) A. public void moreA(int... nums) {} B. public void moreB(String values, int... nums) {} C. public void moreC(int... nums, String values) {} D. public void moreD(String... values, int... nums) {} E. public void moreE(String[] values, ...int nums) {} F. public void moreF(String... values, int[] nums) {} G. public void moreG(String[] values, int[] nums) {}

A, C, D. Options A and C are correct because a void method is allowed to have a return statement as long as it doesn't try to return a value. Options B and G do not compile because null requires a reference object as the return type. void is not a reference object since it is a marker for no return type. int is not a reference object since it is a primitive. Option D is correct because it returns an int value. Option E does not compile because it tries to return a double when the return type is int. Since a double cannot be assigned to an int, it cannot be returned as one either. Option F does not compile because no value is actually returned.

Which of the following methods compile? (Choose all that apply) A. public void methodA() { return;} B. public void methodB() { return null;} C. public void methodD() {} D. public int methodD() { return 9;} E. public int methodE() { return 9.0;} F. public int methodF() { return;} G. public int methodG() { return null;}

A, G. Options B and C don't compile because the constructor name must match the classname. Since Java is case sensitive, these don't match. Options D, E, and F all compile and provide one user-defined constructor. Since a constructor is coded, a default constructor isn't supplied. Option G defines a method, but not a constructor. Option A does not define a constructor, either. Since no constructor is coded, a default constructor is provided for options A and G.

Which of these classes compile and use a default constructor? (Choose all that apply) A. public class Bird { } B. public class Bird { public bird() {} } C. public class Bird { public bird(String name) {} } D. public class Bird { public Bird() {} } E. public class Bird { Bird(String name) {} } F. public class Bird { private Bird(int age) {} } G. public class Bird { void Bird() { }

Notice that all of these examples have parentheses around the parameter list except the one that takes only one parameter and doesn't specify the type. Line 3 takes 0 parameters and always returns the Boolean true. Line 4 takes one parameter and calls a method on it, returning the result. Line 5 does the same except that it explicitly defi nes the type of the variable. Lines 6 and 7 take two parameters and ignore one of them—there isn't a rule that says you must use all defi ned parameters.

Will these compile? 3: print(() -> true); 4: print(a -> a.startsWith("test")); 5: print((String a) -> a.startsWith("test")); 6: print((a, b) -> a.startsWith("test")); 7: print((String a, String b) -> a.startsWith("test"));

The fi rst line needs parentheses around the parameter list. Remember that the parentheses are only optional when there is one parameter and it doesn't have a type declared. The second line is missing the return keyword. The last line is missing the semicolon.

Will these compile? print(a, b -> a.startsWith("test")); print(a -> { a.startsWith("test"); }); print(a -> { return a.startsWith("test") });

No. There is one more issue you might see with lambdas. We've been defi ning an argument list in our lambda expressions. Since Java doesn't allow us to redeclare a local variable, the following is an issue.

Will this compile? (a, b) -> { int a = 0; return 5;}

Yes.

Will this compile? (a, b) -> { int c = 0; return 5;}

The method can only be called from classes in the same package. This one is tricky because there is no keyword for default access. You simply omit the access modifier.

default access modifier

Second line doesn't compile There's only one more scenario with static imports. In Chapter 1, you learned that importing two classes with the same name gives a compiler error. This is true of static imports as well. The compiler will complain if you try to explicitly do a static import of two methods with the same name or two static variables with the same name. Luckily when this happens, we can just refer to the static members via their classname in the code instead of trying to use a static import.

import static statics.A.TYPE; import static statics.B.TYPE;

Lines 15 and 16 do not compile. This time a Bird reference is used. It is created on line 14. Bird is in a different package, and this code isn't inheriting from Bird, so it doesn't get to use protected members. Say what now? We just got through saying repeatedly that Swan inherits from Bird. And it does. However, the variable reference isn't a Swan. The code just happens to be in the Swan class.

package pond.shore; public class Bird { protected String text = "floating"; protected void floatInWater() { System.out.println(text); } } 1: package pond.swan; 2: import pond.shore.Bird; // in different package than Bird 3: public class Swan extends Bird { // but subclass of bird 4: public void swim() { 5: floatInWater(); / 6: System.out.println(text); 7: } 13: public void helpOtherBirdSwim() { 14: Bird other = new Bird(); 15: other.floatInWater(); 16: System.out.println(other.text); 17: } 18: }

Compiler error at lines 17, 20, 21. Line 14 declares a static variable that is not fi nal. It can be assigned as many times as we like. Line 15 declares a fi nal variable without initializing it. This means we can initialize it exactly once in a static block. Line 22 doesn't compile because this is the second attempt. Line 16 declares a fi nal variable and initializes it at the same time. We are not allowed to assign it again, so line 21 doesn't compile. Line 17 declares a fi nal variable that never gets initialized. The compiler gives a compiler error because it knows that the static blocks are the only place the variable could possibly get initialized. Since the programmer forgot, this is clearly an error

14: private static int one; 15: private static final int two; 16: private static final int three = 3; 17: private static final int four; 18: static { 19: one = 1; 20: two = 2; 21: three = 3; 22: two = 4; 23: }

Compiler error on lines 1, 3, 6 Line 1 tries to use a static import to import a class. Remember that static imports are only for importing static members. Regular imports are for importing a class. Line 3 tries to see if you are paying attention to the order of keywords. The syntax is import static and not vice versa. Line 6 is sneaky. We imported the asList method on line 2. However, we did not import the Arrays class anywhere. This makes it okay to write asList("one"); but not Arrays.asList("one");

1: import static java.util.Arrays; 2: import static java.util.Arrays.asList; 3: static import java.util.Arrays.*; 4: public class BadStaticImports { 5: public static void main(String[] args) { 6: Arrays.asList("one"); 7: } }

The correct answer is 2 4 6 8 5. Let's walk through why that is. There is no superclass, so we jump right to rule 2—the statics. There are three static blocks: on lines 2, 5, and 7. They run in that order. The static block on line 2 calls the add() method, which prints 2. The static block on line 5 calls the add() method, which prints 4. The last static block, on line 7, calls new to instantiate the object. This means we can go on to rule 3 to look at the instance variables and instance initializers. There are two of those: on lines 6 and 8. They both call the add() method and print 6 and 8, respectively. Finally, we go on to rule 4 and call the constructor, which calls the add() method one more time and prints 5.

1: public class YetMoreInitializationOrder { 2: static { add(2); } 3: static void add(int num) { System.out.print(num + " "); } 4: YetMoreInitializationOrder() { add(5); } 5: static { add(4); } 6: { add(6); } 7: static { new YetMoreInitializationOrder(); } 8: { add(8); } 9: public static void main(String[] args) { } }

4 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. Let's look at an example: On line 3, num is assigned the value of 4. On line 4, we call a method. On line 8, the num parameter in the method gets set to 8. Although this parameter has the same name as the variable on line 3, this is a coincidence. The name could be anything. The exam will often use the same name to try to confuse you. The variable on line 3 never changes because no assignments are made to it.

2: public static void main(String[] args) { 3: int num = 4; 4: newNumber(5); 5: System.out.println(num); // 4 6: } 7: public static void newNumber(int num) { 8: num = 8; 9: }

You can use an instance of the object to call a static method. The compiler checks for the type of the reference and uses that instead of the object. Believe it or not, this code outputs 0 twice. Line 6 sees that k is a Koala and count is a static variable, so it reads that static variable. Line 8 does the same thing. Java doesn't care that k happens to be null. Since we are looking for a static, it doesn't matter. Remember to look at the reference type for a variable when you see a static method or variable. The exam creators will try to trick you into thinking a NullPointerException is thrown because the variable happens to be null. Don't be fooled!

5: Koala k = new Koala(); 6: System.out.println(k.count); // k is a Koala 7: k = null; 8: System.out.println(k.count);

C. Within the constructor numSpots refers to the constructor parameter. The instance variable is hidden because they have the same name. this.numSpots tells Java to use the instance variable. In the main() method, numSpots refers to the instance variable. Option A sets the constructor parameter to itself, leaving the instance variable as 0. Option B sets the constructor parameter to the value of the instance variable, making them both 0. Option C is correct, setting the instance variable to the value of the constructor parameter. Options D and E do not compile.

A. numSpots = numSpots; B. numSpots = this.numSpots; . C. this.numSpots = numSpots; D. numSpots = super.numSpots; E. super.numSpots = numSpots; F. None of the above.

Yes. As you can see, we can overload by changing anything in the parameter list. We can have a different type, more types, or the same types in a different order. Also notice that the access modifi er and exception list are irrelevant to overloading.

Are these valid overloaded methods? public void fly(int numMiles) { } public void fly(short numFeet) { } public boolean fly() { return false; } void fly(int numMiles, short numFeet) { } public void fly(short numFeet, int numMiles) throws Exception { }

In this case, the output is Webby because the method merely calls a method on the parameter. It doesn't reassign name to a different object. In Figure 4.4, you can see how pass-by-value is still used. s is a copy of the variable name. Both point to the same StringBuilder, which means that changes made to the StringBuilder are available to both references.

public static void main(String[] args) { StringBuilder name = new StringBuilder(); speak(name); System.out.println(name); } public static void speak(StringBuilder s) { s.append("Webby"); }

The correct answer is Webby. Just as in the primitive example, the variable assignment is only to the method parameter and doesn't affect the caller. Notice how we keep talking about variable assignments. This is because we can call methods on the parameters.

public static void main(String[] args) { String name = "Webby"; speak(name); System.out.println(name); } public static void speak(String name) { name = "Sparky"; }

Swan is not in the same package as Bird, but does extend it—which implies it has access to the protected members of Bird since it is a subclass. And it does. Lines 5 and 6 refer to protected members via inheriting them. Lines 10 and 11 also successfully use protected members of Bird. This is allowed because these lines refer to a Swan object. Swan inherits from Bird so this is okay. It is sort of a two-phase check. The Swan class is allowed to use protected members of Bird and we are referring to a Swan object. Granted, it is a Swan object created on line 9 rather than an inherited one, but it is still a Swan object.

package pond.shore; public class Bird { protected String text = "floating"; protected void floatInWater() { System.out.println(text); } } 1: package pond.swan; 2: import pond.shore.Bird; // in different package than Bird 3: public class Swan extends Bird { // but subclass of bird 4: public void swim() { 5: floatInWater(); // package access to superclass 6: System.out.println(text); // package access to superclass 7: } 8: public void helpOtherSwanSwim() { 9: Swan other = new Swan(); 10: other.floatInWater(); // package access to superclass 11: System.out.println(other.text);// package access to superclass 12: }}

This code doesn't compile because we are not in the Goose class. The floatInWater() method is declared in Bird. GooseWatcher is not in the same package as Bird, nor does it extend Bird. Goose extends Bird. That only lets Goose refer to floatInWater() and not callers of Goose

package pond.shore; public class Bird { protected String text = "floating"; protected void floatInWater() { System.out.println(text); } } package pond.duck; import pond.goose.Goose; public class GooseWatcher { public void watch() { Goose goose = new Goose(); goose.floatInWater(); } }

The fi rst method is fi ne. In fact, it is equivalent to the Swan example. Goose extends Bird. Since we are in the Goose subclass and referring to a Goose reference, it can access protected members. The second method is a problem. Although the object happens to be a Goose, it is stored in a Bird reference. We are not allowed to refer to members of the Bird class since we are not in the same package and Bird is not a subclass of Bird

package pond.shore; public class Bird { protected String text = "floating"; protected void floatInWater() { System.out.println(text); } } package pond.goose; import pond.shore.Bird; public class Goose extends Bird { public void helpGooseSwim() { Goose other = new Goose(); other.floatInWater(); System.out.println(other.text); } public void helpOtherGooseSwim() { Bird other = new Goose(); other.floatInWater(); System.out.println(other.text); } }

To review, Java uses pass-by-value to get data into a method. Assigning a new primitive or reference to a parameter doesn't change the caller. Calling methods on a reference to an object does affect the caller. Getting data back from a method is easier. A copy is made of the primitive or reference and returned from the method. Most of the time, this returned value is used. For example, it might be stored in a variable. If the returned value is not used, the result is ignored.

pass-by-value

The method can only be called from within the same class.

private access modifier

The method can only be called from classes in the same package or subclasses.

protected access modifier

The method can be called from any class.

public access modifier

3 Each time the constructor gets called, it increments count by 1. This example relies on the fact that static (and instance) variables are automatically initialized to the default value for that type, which is 0 for int. See Chapter 1 to review the default values. Also notice that we didn't write Counter.count. We could have. It isn't necessary because we are already in that class so the compiler can infer it.

public class Counter { private static int count; public Counter() { count++; } public static void main(String[] args) { Counter c1 = new Counter(); Counter c2 = new Counter(); Counter c3 = new Counter(); System.out.println(count); } }

The answer is int long. The fi rst call passes an int and sees an exact match. The second call passes a long and also sees an exact match. If we comment out the overloaded method with the int parameter list, the output becomes long long. Java has no problem calling a larger primitive. However, it will not do so unless a better match is not found. Note that Java can only accept wider types. An int can be passed to a method taking a long parameter. Java will not automatically convert to a narrower type. If you want to pass a long to a method taking an int parameter, you have to add a cast to explicitly say narrowing is okay.

public class Plane { public void fly(int i) { System.out.print("int "); } public void fly(long l) { System.out.print("long "); } public static void main(String[] args) { Plane p = new Plane(); p.fly(123); p.fly(123L); } }

The answer is "string object". The fi rst call is a String and fi nds a direct match. There's no reason to use the Object version when there is a nice String parameter list just waiting to be called. The second call looks for an int parameter list. When it doesn't fi nd one, it autoboxes to Integer. Since it still doesn't fi nd a match, it goes to the Object one.

public class ReferenceTypes { public void fly(String s) { System.out.print("string "); } public void fly(Object o) { System.out.print("object "); } public static void main(String[] args) { ReferenceTypes r = new ReferenceTypes(); r.fly("test"); r.fly(56); } }

The compiler will give you an error about making a static reference to a nonstatic method. If we fi x this by adding static to third(), we create a new problem. Can you fi gure out what it is? All this does is move the problem. Now, third() is referring to nonstatic name. Adding static to name as well would solve the problem. Another solution would have been to call third as an instance method—for example, new Static().third();. The exam creators like this topic. A static method or instance method can call a static method because static methods don't require an object to use. Only an instance method can call another instance method on the same class without using a reference variable, because instance methods do require an object. Similar logic applies for the instance and static variables.

public class Static { private String name = "Static class"; public static void first() { } public static void second() { } public void third() { System.out.println(name); } public static void main(String args[]) { first(); second(); third(); } }


Ensembles d'études connexes

Chapter 28 The Structure of Space and Time

View Set

Topic 4 Lesson 6 The Spanish-American War

View Set

TEST: HUMAN ANATOMY AND PHYSIOLOGY

View Set

Bio-182: Exam 3 Amplifier: Animal Form and Function

View Set

CHAPTER 7 QUIZ ANSWERS youtube marketing MARKETING STRATEGIES: A GUIDE TO SOCIAL MEDIA AND DIGITAL MARKETING edify stukent

View Set