Sub topic 3
Creating Objects with `new` and Accessing Members
A class describes a kind of object. An object is a separate item made from that description. For example, a Lamp class can describe lamps, while each lamp object has its own color and brightness.
In Java, you use new to create an object. Then you use a dot to access its members. A member is a field or method that belongs to a class. A field stores data. A method describes an action the object can perform.
In this chapter, you will create two lamp objects, change their fields, and call their methods.
A complete example
Save this program in a file named Main.java. You need the Java Development Kit, or JDK, installed to compile and run it. The JDK includes the tools for turning Java source code into a program and running it.
class Lamp {
String color = "white";
int brightness = 0;
boolean on = false;
void turnOn() {
on = true;
}
void setBrightness(int level) {
brightness = level;
}
int getBrightness() {
return brightness;
}
void showStatus() {
System.out.println(color + ": on=" + on
+ ", brightness=" + brightness);
}
}
public class Main {
public static void main(String[] args) {
Lamp deskLamp = new Lamp();
Lamp floorLamp = new Lamp();
deskLamp.color = "blue";
deskLamp.turnOn();
deskLamp.setBrightness(3);
System.out.println("Desk color: " + deskLamp.color);
deskLamp.showStatus();
floorLamp.showStatus();
floorLamp.color = "red";
floorLamp.turnOn();
floorLamp.setBrightness(2);
floorLamp.showStatus();
int level = deskLamp.getBrightness();
System.out.println("Desk brightness: " + level);
}
}Open a terminal in the folder containing Main.java. A terminal lets you enter commands for your computer to run. Enter:
javac Main.java
java MainThe first command compiles the source code. Compiling means translating the code into a form Java can run. The second command runs the program. Its output is:
Desk color: blue
blue: on=true, brightness=3
white: on=false, brightness=0
red: on=true, brightness=2
Desk brightness: 3The file contains two classes. Lamp describes the objects. Main contains the main method, where Java starts this program. For now, you can treat the words around main as the required starting pattern.
Create an object with `new`
Look at this line:
Lamp deskLamp = new Lamp();
Each part has a job:
Lampis the variable’s type. A type tells Java what kind of value a variable can hold.deskLampis the variable’s name.new Lamp()creates a newLampobject.=assigns the result todeskLamp.;marks the end of the statement.
The result of new Lamp() is a reference. A reference is a value that lets the program reach an object. The variable deskLamp holds that reference, so you can use the variable to work with the new lamp.
The parentheses in new Lamp() are required. They are part of the call that sets up the object. A constructor is the part of a class used when an object is created. Since this Lamp class does not declare a constructor, Java provides one that takes no values between the parentheses. You will study constructors in more detail later.
The next line also uses new:
Lamp floorLamp = new Lamp();
This creates a second object. It does not simply give the first lamp another name. Each use of new Lamp() in this example creates a separate lamp.
You can also declare a variable first and create its object later:
Lamp deskLamp;
deskLamp = new Lamp();
A local variable is a variable declared inside a method, such as deskLamp inside main. Declaring a local variable alone does not create an object. You must assign it a value before you use it.
Starting field values
Each new lamp starts with the values written in the Lamp class:
| Field | Type | Starting value |
|---|---|---|
| `color` | `String`, a type for text | `"white"` |
| `brightness` | `int`, a type for whole numbers | `0` |
| `on` | `boolean`, a type with values `true` and `false` | `false` |
The values after the = signs in the class give each new lamp its starting state. An object’s state is the set of data it currently holds.
Both lamps start white, with brightness 0, and switched off. After the program changes deskLamp, the two objects have different states:
Changing one lamp does not change the other. That is why the first call to floorLamp.showStatus() still prints white: on=false, brightness=0.
Read and change fields
Use a dot after an object variable to reach one of its fields:
deskLamp.color
You can read that field in an expression. An expression is a piece of code that produces a value. In the example, this line reads the color and prints it:
System.out.println("Desk color: " + deskLamp.color);
The + joins the text and the field value for printing. At that point, the color is "blue", so the line prints Desk color: blue.
You can also assign a new value to a field:
deskLamp.color = "blue";
Java finds the object through deskLamp and changes that object’s color field. The field value must match its type. For example, color is a String, so assigning the whole number 3 to it would cause a compile error.
Field names are case-sensitive. That means color and Color are different names. The dot must also be followed by a field that exists in the variable’s type. There is no deskLamp.weight field in this example.
Why are these fields accessible?
The example places both classes in the same file and does not put an access word before the fields or methods. This makes those members available to Main in this example.
Direct field access is useful for learning the dot syntax. It is not always the best design: other classes can use access controls to limit which fields are changed from outside. You will learn more about protecting state in a later chapter.
Call methods on an object
A method call asks an object to perform an action. It also uses a dot:
deskLamp.turnOn();
The variable before the dot selects the object. The name after the dot selects the method. The parentheses are required, even when there is nothing between them.
Inside turnOn, this line runs:
on = true;
Here, on means the field of the lamp receiving the call. Because the program called deskLamp.turnOn(), the desk lamp becomes on. The floor lamp remains off until the program calls floorLamp.turnOn().
Pass a value to a method
Some methods need information to do their work:
deskLamp.setBrightness(3);
The 3 is an argument: a value supplied in a method call. The method receives it in level, which is a parameter. A parameter is a named place for a value a method receives.
In setBrightness, the statement brightness = level; stores that value in the receiving lamp’s field. Since level has type int, the call must supply a whole-number value.
The example does not check whether the number is a sensible brightness. It simply stores the value. Also, setting brightness does not automatically turn a lamp on; the program makes a separate call to turnOn().
Use a value returned by a method
A method can give a result back to the code that called it. The getBrightness method returns an int:
int level = deskLamp.getBrightness();
The method reads the desk lamp’s brightness field and returns its value. The assignment then stores that value in the local variable level.
In contrast, turnOn, setBrightness, and showStatus have void before their names. void means that the method does not return a value. You can call deskLamp.turnOn();, but you cannot assign a result from that call to an int.
Common mistakes
When a program does not compile, check the object creation and member access syntax:
- Missing
new:Lamp deskLamp;declares a variable but does not create a lamp. - Missing parentheses: write
new Lamp()anddeskLamp.turnOn(), notnew LampordeskLamp.turnOn. - Wrong spelling or capital letters:
deskLamp.colorworks, butdeskLamp.Colornames a different field. - Wrong value type:
deskLamp.setBrightness(3)uses anint;deskLamp.setBrightness("bright")supplies text instead. - Wrong number of arguments:
turnOn()takes none, whilesetBrightnesstakes oneint. - Missing semicolon: finish statements such as assignments and method calls with
;.
If you change the source file, run javac Main.java again before java Main. Otherwise, you may run the previously compiled version instead of your latest changes.
Try it yourself
Change the program so the desk lamp is green and has brightness 5. Compile and run it again. Check both the status line and the final brightness line. Then check that the floor lamp’s first status line still shows its starting values.
Exercise
What does new Lamp() do, and what does deskLamp hold after Lamp deskLamp = new Lamp();?
Show answer
new Lamp() creates a new lamp object. deskLamp holds a reference that lets the program reach that object.
Exercise
After creating two separate lamps, you call deskLamp.setBrightness(5). What is the floor lamp’s brightness if nothing has changed it?
Show answer
It is still 0. Each lamp has its own brightness field.
Exercise
Why does deskLamp.getBrightness() need parentheses, while deskLamp.color does not?
Show answer
getBrightness is a method, so calling it requires parentheses. color is a field, so accessing it does not.