3.6. Accessing object fields

[2.3] Know how to read or write to object fields

In this section, you’ll learn what object fields are and how to read, initialize, and modify them. You’ll also learn the correct notation used to call methods on objects. Access modifiers also determine whether you can call a method on an object.

3.6.1. What is an object field?

An object field is another name for an instance variable defined in a class. I’ve often seen certification aspirants who are confused over whether the object fields are the same as instance variables of a class.

Here’s an example of the class Star:

In the preceding example, defines an instance variable, starAge. defines a setter method, setAge. A setter (or mutator) method is used to set the value of a variable. defines a getter (or accessor) method, getAge. A getter method is used to retrieve the value of a variable. In this example, the object field is starAge, not age or newAge. The name of an object field is not determined by the name of its getter or setter methods.

JavaBeans properties and object fields

The reason for the confusion over the name of the object field is that Java classes can also be used to define visual or nonvisual components called JavaBeans, which are used in visual and nonvisual environments like Spring, Hibernate, and others. These classes are supposed to define getter and setter methods to retrieve and set the properties of the visual components. If a visual JavaBean component defines a property such as age, then the name of its getter and setter methods will be getAge and setAge. For a JavaBean, you don’t have to worry about the name of the variable that’s used to store the value of this property. In a JavaBean, an object field thisIsMyAge- can be used to store the value of its property age.

Note that the JavaBeans I mentioned aren’t Enterprise JavaBeans. Enterprise JavaBeans are used in enterprise applications written in Java, which run on servers.

3.6.2. Read and write object fields

The OCA Java SE 8 Programmer I exam will test you on how to read values from and write them to fields of an object, which can be accomplished by any of following:

  • Using methods to read and write object fields
  • Using constructors to write values to object fields
  • Directly accessing instance variables to read and write object fields
Exam Tip

Although object fields can be manipulated by direct access, it isn’t a recommended practice. It makes an object vulnerable to invalid data. Such a class isn’t well encapsulated.

This exam objective (2.3) will also test your understanding of how to assign different values to the same object fields for multiple objects. Let’s start with an example:

In the class Employee, defines two object fields: name and age. It defines a (no-argument) constructor. And assigns a value of 22 to its field age. This class also defines a method setName, where assigns the value passed to it to the object field name. The method printEmp is used to print the values of object fields name and age.

The following is the definition of a class, Office, which creates two instances, e1 and e2, of the class Employee and assigns values to its fields. Let’s look at the definition of the class Office:

class Office {
    public static void main(String args[]) {
        Employee e1 = new Employee();
        Employee e2 = new Employee();
        e1.name = "Selvan";
        e2.setName("Harry");
        e1.printEmp();
        e2.printEmp();
    }
}

This is the output of the preceding code:

name = Selvan age = 22
name = Harry age = 22

Figure 3.22 defines object diagrams (a diagram with the name and type of an object, the name of the object’s fields, and their corresponding values), which will help you to better understand the preceding output.

Figure 3.22. Two objects of the class Employee

You can access the object field name of the object of the class Employee either by using its variable name or by using the method setName. The following line of code assigns a value Selvan to the field name of object e1:

e1.name = "Selvan";

The following line of code uses the method setName to assign a value of Harry to the field name of object e2:

e2.setName("Harry");

Because the constructor of the class Employee assigns a value of 22 to the variable age, objects e1 and e2 both contain the same value, 22.

What happens if you don’t assign any value to an object field and try to print out its value? All the instance variables (object fields) are assigned their default values if you try to access or read their values before writing any values to them:

The output of the preceding code is as follows (the default value of an object is null and int is 0):

name = null age = 0

What happens if you change the access modifier of the variable name to private, as shown here (modified code in bold)?

You won’t be able to set the value of the object field name as follows:

e1.name = "Selvan";

This line of code won’t compile. Instead, it complains that the variable name has private access in the class Employee and can’t be accessed from any other class:

Office.java:6:  name has private access in Employee
            e1.name = "Selvan";

When you answer questions on reading values from and writing them to an object field, watch out for the following points in the exam:

  • Access modifier of the object field
  • Access modifiers of methods used to read and write the value of the object field
  • Constructors that assign values to object fields

3.6.3. Calling methods on objects

You can call methods defined in a class using an object reference variable. In this exam objective, this exam will specifically test you on the following:

  • The correct notation used to call a method on an object reference variable
  • The right number of method parameters that must be passed to a method
  • The return value of a method that’s assigned to a variable

Java uses the dot notation (.) to execute a method on a reference variable. Suppose the class Employee is defined as follows:

You can create an object of class Employee and call the method setName on it like this:

Employee e1 = new Employee();
e1.setName("Java");

The following method invocations aren’t valid in Java:

When you call a method, you must pass to it the exact number of method parameters that are defined by it. In the previous definition of the Employee class, the method setName defines a method parameter of type String. You can pass a literal value or a variable to a method, as a method parameter. The following code invocations are correct:

Exam Tip

A call to a method must be followed by passing values to all its method parameters. For a method that defines one or more method parameters, you can’t call the method followed by () to indicate it doesn’t need to be passed values.

If the parameter list of the called method defines a variable argument at the rightmost position, you can call the method with a variable number of arguments. Let’s add a method daysOffWork in the class Employee that accepts a variable list of arguments (modifications in bold):

class Employee {
    private String name;
    public void setName(String val) {
        name = val;
    }
    public int daysOffWork(int... days) {
        int daysOff = 0;
        for (int i = 0; i < days.length; i++)
            daysOff += days[i];
        return daysOff;
    }

You can call this method using a variable list of arguments:

The output of the preceding code is as follows:

10
6
Exam Tip

Methods that accept varargs parameters can be called with a different count of actual arguments. Also, a method that accepts a vararg can be invoked with an array in place of the vararg.

Let’s add the method getName to the class Employee that returns a String value (changes in bold):

class Employee {
    private String name;
    public void setName(String val) {
        name = val;
    }

    public String getName() {
        return name;
    }
}

You can assign the String value returned from the method getName to a String variable or pass it on to another method, as follows:

In the preceding code, the return type of the method setName is void; therefore, you can’t use it to assign a value to a variable:

Also, you can’t assign a return value of a method to an incompatible variable, as follows:

You can read and write object fields either by using methods or by directly accessing the instance variables of a class. But it’s not a good idea to enable access to the instance variables outside a class.

In the next section, you’ll see the risks of exposing instance variables outside a class and the benefits of 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
13.58.121.8