Sub topic 2
Initializing objects with constructors
A constructor is a special part of a class that sets up a new object. It has the same name as the class and no return type. Java calls it when you create an object with new.
Save this example as Counter.java. A counter holds a whole number and can increase it.
class Counter {
private int value;
Counter() {
this(0);
}
Counter(int initialValue) {
if (initialValue < 0) {
throw new IllegalArgumentException("Value must be nonnegative");
}
this.value = initialValue;
}
void increment() {
if (value < Integer.MAX_VALUE) {
value++;
}
}
int getValue() {
return value;
}
public static void main(String[] args) {
Counter first = new Counter();
Counter second = new Counter(3);
first.increment();
System.out.println(first.getValue());
System.out.println(second.getValue());
}
}Compile and run it with the Java development tools:
javac Counter.java
java CounterThe output is 1, then 3, on separate lines.
Overloading and delegation
A parameter is a named input in a constructor or method. An argument is the value passed to it. In new Counter(3), initialValue is the parameter, and 3 is the argument.
Constructor overloading means providing constructors with different parameter lists. Here, Counter() takes no arguments, while Counter(int initialValue) takes one whole number.
The call this(0) delegates, or passes the setup work, to the other constructor. It must be the first statement in the constructor. This lets both constructors use the same check.
Controlling access to state
A field is a variable stored in an object. The field value holds the counter’s state. The keyword private means code outside Counter cannot access it directly.
A method is a named action an object can perform. The methods increment and getValue provide controlled ways to change and read the value. Hiding state and controlling access to it is called encapsulation.
In this.value, this refers to the current object. It makes clear that value is that object’s field.
Validating values
Validation is checking that input meets a rule. The constructor rejects a negative argument by throwing an exception, which signals a problem and stops normal execution.
An invariant is a rule that must remain true for an object’s state. Here, the value must stay nonnegative. The constructor checks the starting value, and increment stops at Integer.MAX_VALUE, the largest value an int can hold. Without that limit, increasing it could produce a negative value.
Exercise
What happens when you write new Counter(-1), and why?
Show answer
The constructor throws an IllegalArgumentException because a negative starting value would break the counter’s nonnegative invariant.