Sub topic 3
Class-level state and behavior with static
A class is a definition for objects. An object is a value created from a class. A field is a variable that holds data, and a method is a named operation.
A static field belongs to the class, not to one object. All objects of that class share it. A static method also belongs to the class, so you can call it without an object.
Save this example as Main.java, then run javac Main.java and java Main.
class Person {
private final String name;
Person(String name) {
this.name = name;
}
String getName() {
return name;
}
}
final class Employee extends Person {
private static int created;
private final int id;
Employee(String name, int id) {
super(name);
this.id = id;
created++;
}
static int getCreated() {
return created;
}
}
public class Main {
public static void main(String[] args) {
Employee first = new Employee("Ada", 7);
Employee second = new Employee("Ada", 7);
System.out.println(Employee.getCreated());
System.out.println(first == second);
System.out.println(first.getName().equals(second.getName()));
}
}The output is:
2
false
truecreated starts at zero and counts the Employee objects made. The call Employee.getCreated() uses the class name to call the static method.
Subclass construction
A subclass is a class that extends another class. Employee extends Person, its superclass. A constructor is the code that sets up a new object. The call super(name) runs the Person constructor before the Employee constructor sets id.
Initialization order
For an Employee, Java first gives its object fields default values, such as 0 or null. It then runs Person’s field initializers and constructor body, followed by Employee’s field initializers and constructor body. A field initializer is a value given where a field is declared.
Identity and logical equality
A reference is a value that points to an object. For references, == checks identity: whether both point to the same object. Here, first and second point to different objects.
Logical equality means having matching values. The example uses the String method equals to compare the two names. It does not compare the employees themselves: Employee does not define its own logical equality.
Immutable objects
An immutable object cannot change its state after construction. The Employee fields are private, so outside code cannot change them. They are also final, so they can be assigned only once. String is immutable, and the final class cannot be extended by a subclass that adds changing state.
The shared created count can still change; it is class state, not an individual employee’s state.
Exercise
If you create a third Employee with the name "Ada", what will Employee.getCreated() return, and will it be identical to first?
Show answer
It will return 3. The new employee is a different object, so it is not identical to first.