A.3 Chapter 3: Methods and encapsulation

Chapter 3 includes three Twist in the Tale exercises.

A.3.1 Twist in the Tale 3.1

Purpose: In the same way that the class TestPhone in this exercise defines a local variable with the same name as its instance variable, I strongly recommend that you try out different combinations of defining variables with the same name in a class, but with different scope.

Answer: a

Explanation: The class Phone defines an instance variable with the name phoneNumber. The method setNumber also defines a local variable phoneNumber and assigns a value to its local variable. A local variable takes precedence over an instance variable defined in the class with the same names. Because there is no change in the value of the instance variable phoneNumber, 123456789 is printed to the console from the method main, defined in the class TestPhone.

A.3.2 Twist in the Tale 3.2

Purpose: To learn that recursive or circular calls to constructors aren’t allowed.

Answer: The code fails to compile, with the following compilation error message:

Employee.java:4: error: recursive constructor invocation
    Employee() {
    ^
1 error

Explanation: A method calling itself is called recursion. Two or more methods calling each other, in a circular manner, is called circular method calling.

Starting in Java version 1.4.1, the Java compiler won’t compile code with recursive or circular constructors. A constructor is used to initialize an object, so it doesn’t make sense to allow recursive calls to a constructor. You can initialize an object once and then modify it. You can’t initialize an object multiple times.

In case you’re wondering whether you can call a constructor conditionally from another constructor, you can’t. A call to a constructor must be the first statement:

Also, circular constructor calls aren’t allowed:

The previous example doesn’t compile, with the following compilation error message:

Employee.java:8: error: recursive constructor invocation
    Employee(String newName, int newAge) {
    ^
1 error

Note that similar recursive or circular calls defined in methods don’t result in compilation errors.

A.3.3 Twist in the Tale 3.3

Purpose: A class with public instance variable(s) can never be designated as a well-encapsulated class.

Answer: e

Explanation: This question tries to trick you by defining options that play with multiple access modifiers for methods getWeight and setWeight. Because the instance variable model of the class Phone is defined using the public access modifier (and no proposed options address this issue), it’s accessible outside this class. So Phone isn’t a well-encapsulated class.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.227.4