Sub topic 1
Classes as Definitions, Objects as Instances
Classes and objects
A class is a definition that describes a kind of object. An object is a separate item created from a class. Each object is also called an instance of that class.
For example, a Lamp class can describe lamps. You can create two lamp objects from it. Turning one on does not have to turn the other on.
Fields and methods
A field is a variable stored in an object. It holds part of the object’s state, or current data. A method is a named set of instructions that an object can perform. Its actions are the object’s behavior.
Our Lamp class has an on field. Its type, boolean, holds either true or false. The turnOn method changes that field to true.
Create and use objects
The keyword new creates an object. A variable can hold a way to find that object. Use a dot to access a field or call a method.
Save this program as Main.java:
class Lamp {
boolean on = false;
void turnOn() {
on = true;
}
}
public class Main {
public static void main(String[] args) {
Lamp first = new Lamp();
Lamp second = new Lamp();
Lamp shared = first;
shared.turnOn();
System.out.println(first.on); // true
System.out.println(second.on); // false
System.out.println(first == shared); // true
System.out.println(first == second); // false
Lamp missing = null;
System.out.println(missing == null); // true
}
}The main method is where the program starts. Run these commands in a terminal, a tool for entering commands:
javac Main.java
java MainThe first command compiles the program, or translates it so Java can run it. The second runs it. The comments after // show the expected output.
References, null, and identity
A reference is a value that lets you find an object. Both first and shared refer to the same lamp. Calling shared.turnOn() therefore changes what first.on reports. The second variable refers to a separate lamp.
Object identity means whether two references point to the very same object. For references, == checks identity. It does not compare the objects’ field values.
The value null means a reference points to no object. Trying to access a field or method through it causes an error.
Exercise
If you call second.turnOn() after the code above, what will first == second show?
Show answer
It will still show false. Both lamps are on, but they are separate objects.