Читать книгу OCP Oracle Certified Professional Java SE 17 Developer Study Guide - Jeanne Boyarsky - Страница 88
Reading and Writing Member Fields
ОглавлениеIt's possible to read and write instance variables directly from the caller. In this example, a mother swan lays eggs:
public class Swan { int numberEggs; // instance variable public static void main(String[] args) { Swan mother = new Swan(); mother.numberEggs = 1; // set variable System.out.println(mother.numberEggs); // read variable } }
The “caller” in this case is the main()
method, which could be in the same class or in another class. This class sets numberEggs
to 1
and then reads numberEggs
directly to print it out. In Chapter 5, you learn how to use encapsulation to protect the Swan
class from having someone set a negative number of eggs.
You can even read values of already initialized fields on a line initializing a new field:
1: public class Name { 2: String first = "Theodore"; 3: String last = "Moose"; 4: String full = first + last; 5: }
Lines 2 and 3 both write to fields. Line 4 both reads and writes data. It reads the fields first
and last
. It then writes the field full
.