Sub topic 2
Representing State and Behavior with Fields and Methods
A class is a definition for a kind of object. An object is an individual thing made from a class. For example, a Thermometer class can describe many thermometer objects.
A field is a variable that belongs to an object. Fields hold the object’s state: the information it currently has. A thermometer might have a label and a temperature as fields.
A method is a named set of instructions that can be called to perform a task. Methods describe behavior: what an object can do. A thermometer might have methods that change its temperature or report a reading.
A working thermometer
This example makes two thermometer objects. Each object has its own label and temperature. The methods read or change the fields of the object on which they are called.
Save the code in a file named Main.java.
class Thermometer {
String label = "Room";
double temperatureC = 20.0;
void setLabel(String label) {
this.label = label;
}
void warmBy(double amount) {
temperatureC = temperatureC + amount;
}
double getTemperature() {
return temperatureC;
}
double getFahrenheit() {
double fahrenheit = temperatureC * 9.0 / 5.0 + 32.0;
return fahrenheit;
}
void showReading() {
System.out.println(label + ": " + temperatureC + " C");
}
}
public class Main {
public static void main(String[] args) {
Thermometer first = new Thermometer();
Thermometer second = new Thermometer();
first.showReading();
first.setLabel("Kitchen");
first.warmBy(2.5);
first.showReading();
System.out.println("First value: " + first.getTemperature());
System.out.println("First in F: " + first.getFahrenheit());
System.out.println("Second value: " + second.getTemperature());
second.temperatureC = 18.0;
second.showReading();
first.showReading();
}
}To compile the code, which means to translate it into a form Java can run, use javac. Then run the program with java:
javac Main.java
java MainThe output is:
Room: 20.0 C
Kitchen: 22.5 C
First value: 22.5
First in F: 72.5
Second value: 20.0
Room: 18.0 C
Kitchen: 22.5 CThe line beginning with public static void main is where Java starts this program. For this chapter, focus on the fields and methods inside Thermometer.
Fields hold state
Look at the first two lines inside Thermometer:
String label = "Room";
double temperatureC = 20.0;Each line declares a field. A declaration gives a variable a type and a name. A type tells Java what kind of value the variable can hold.
Stringis the type used here for text. The field namedlabelstarts with the text"Room".doubleis a type for numbers that can have a decimal part. The field namedtemperatureCstarts at20.0.
The values after = are initial values. Each new thermometer starts with those values. An object made from a class is also called an instance, so these are instance fields.
The program makes two instances:
Thermometer first = new Thermometer();
Thermometer second = new Thermometer();The new keyword creates an object. The variables first and second let the program use the two objects. You will study object creation in more detail in the next chapter.
Both objects start with the same field values, but their fields are separate. Calling first.warmBy(2.5) changes the temperature of first from 20.0 to 22.5. The temperature of second remains 20.0.
Reading and changing a field
A dot connects an object to one of its fields or methods. For example, second.temperatureC means the temperatureC field of the object named second.
This line changes that field directly:
second.temperatureC = 18.0;Afterward, second.showReading() prints 18.0 C. The final call to first.showReading() still prints 22.5 C. Changing one object did not change the other.
This example allows direct field changes. Later, you will learn how to control access to fields so that changes can go through methods instead.
Initial values and defaults
An explicit initial value is a value written in the field declaration, such as 20.0 in double temperatureC = 20.0;.
If an instance field has no explicit initial value, Java gives it a default:
| Field type | Default value |
|---|---|
| `int` | `0` |
| `double` | `0.0` |
| `boolean`, which holds true or false | `false` |
| `String` or another object type | `null` |
For an object type, null means there is no object value. You will learn more about it in a later chapter.
Defaults apply to fields, not to every variable. In particular, a local variable inside a method must be given a value before the method reads it.
Methods describe behavior
Calling a method means asking it to run. The call first.showReading() asks first to run its showReading method.
The method reads that object’s label and temperatureC fields and prints them:
void showReading() {
System.out.println(label + ": " + temperatureC + " C");
}The parentheses after the method name are part of the method declaration and the call. Here they are empty because showReading needs no input.
Inside this method, System.out.println prints a line. The + signs join the label, text, and temperature for that line.
The word void means the method does not return a value to the place that called it. It can still do work, such as printing or changing a field. Both showReading and warmBy are void methods.
Parameters and arguments
Some methods need input. A parameter is a variable in a method declaration that receives an input value. In warmBy, the parameter is amount:
void warmBy(double amount) {
temperatureC = temperatureC + amount;
}An argument is the value supplied in a method call. In first.warmBy(2.5), the argument is 2.5. During that call, amount has the value 2.5.
The method adds amount to first’s current temperature and stores the result back in the field. The old field value is replaced.
The parameter’s type matters. Here, amount is a double, so the method can work with a decimal value. Calling first.warmBy("hot") would not compile because "hot" is text, not a number.
Return values
A return value is a result a method gives back to its caller. The getTemperature method declares double before its name, so it returns a double:
double getTemperature() {
return temperatureC;
}The return statement sends the field’s current value back to the call. The program uses that result in this line:
System.out.println("First value: " + first.getTemperature());This method does not print by itself. It returns a number, and the surrounding println prints that number.
By contrast, showReading prints inside the method and returns no value. Use a return value when the caller needs a result to use. Use void when the method does its work without giving a result back.
Local variables
A local variable is a variable declared inside a method. It can be used only within the part of the method where it is in scope. Scope is the area of code where a name can be used.
In getFahrenheit, fahrenheit is a local variable:
double fahrenheit = temperatureC * 9.0 / 5.0 + 32.0;
return fahrenheit;The method calculates a value from the object’s Celsius field, stores it in fahrenheit, and returns it. It does not change temperatureC.
Unlike the fields, fahrenheit is not part of the thermometer’s stored state. Code in showReading cannot use that local variable.
Using `this` for the current object
The setLabel method has a parameter named label, just like the field:
void setLabel(String label) {
this.label = label;
}Inside this method, the plain name label refers to the parameter. The word this means the current object: the object on which the method was called. So this.label means that object’s field.
The assignment copies the parameter’s value into the field. After first.setLabel("Kitchen"), the field first.label contains "Kitchen".
If the method used label = label instead, it would assign the parameter’s value back to the parameter. The field would not change.
Common mistakes to check
- Confusing a field with a local variable. A field holds object state; a local variable is declared inside a method.
- Forgetting parentheses in a method call. Write
first.showReading(), notfirst.showReading. - Expecting a
voidmethod to provide a value.showReading()prints a line, but it does not return the reading. - Changing a parameter when you meant to change a same-named field. Use
this.fieldNameto name the current object’s field. - Assuming two objects share their instance fields. In the example, changing
second.temperatureCdoes not changefirst.temperatureC. - Reading a local variable before assigning it a value. Java will not compile that code.
Practice
Exercise
After the two thermometers are created, what does second.getTemperature() return if first.warmBy(2.5) has run but second has not been changed?
Show answer
It returns 20.0. The call changes first's temperature field, not second's.
Exercise
In setLabel(String label), what is the difference between label and this.label?
Show answer
label is the input parameter. this.label is the field of the object on which setLabel was called.
Exercise
Does getFahrenheit change the stored Celsius temperature? Explain why or why not.
Show answer
No. It calculates a local value and returns it. It never assigns a new value to temperatureC.