A constructor initializes a new object. Its name is exactly the class name and it has no return type, not even void. Java runs it as part of a matching new call. If you declare a constructor requiring a topic and minutes, callers must supply those arguments; Java no longer supplies an automatic no-argument constructor.
Parameters and fields can have the same name. this.minutes means the current
object’s field, while minutes by itself refers to the parameter when that name
is in scope. The assignment this.minutes = minutes copies the supplied value
into the field. Writing minutes = minutes assigns the parameter to itself and
leaves the field at its old/default value.
Establish an object before using it
A constructor groups required initialization so a caller cannot accidentally forget one assignment among several. Today the examples use trusted fixed input; Day 6 will check invalid values before accepting them. Constructor parameters describe required data, but types alone cannot say that minutes is positive or a topic is meaningful.
A final field can be assigned in the constructor and then cannot be reassigned. It helps separate fixed properties such as planned duration from changing properties such as completion. Other fields can still change: one final field does not make the whole object unchangeable.
public class Main {
public static void main(String[] args) {
Session java = new Session("Java", 25);
Session reading = new Session("Reading", 10);
System.out.println(java.topic);
System.out.println(reading.minutes);
}
}
class Session {
final String topic;
final int minutes;
Session(String topic, int minutes) {
this.topic = topic;
this.minutes = minutes;
}
}Check your prediction
Java
10 Constructor arguments follow the declared order, just like method arguments. Each call initializes one object. The two final fields cannot later be assigned unrelated values by an update statement.
public class Main {
public static void main(String[] args) {
Box box = new Box(25);
System.out.println(box.value);
}
}
class Box {
int value;
Box(int value) {
value = value;
}
}Check your prediction
0 This is a deliberate bug: the parameter is assigned to itself. Change the left side to this.value and the result becomes 25. The program compiled because both assignments are type-correct; a behavior check exposed the mistake.
public class Main {
public static void main(String[] args) {
Session session = new Session();
System.out.println(session.minutes);
}
}
class Session {
int minutes;
Session(int minutes) {
this.minutes = minutes;
}
}Read the diagnostic
The declared constructor requires an int. Supply a duration in the new call or deliberately design another constructor if there is a useful default. Do not add an arbitrary default just to hide a missing piece of required data.
Your turn
Initialize a reading goal
Define Goal with final String topic and final int target fields. Its constructor receives both values and stores them using this. Add describe() returning topic + ”: ” + target. Create goals Java/30 and Reading/10 and print Java: 30 and Reading: 10.
public class Main {
public static void main(String[] args) {
// Construct and describe two goals.
}
}
class Goal {
// Declare fields, a constructor and describe().
}Hint 1: the idea
Construction supplies required data once. describe reads stored fields from its receiver.
Hint 2: a first step
Use the constructor name Goal with no return type. Write this.topic on the assignment’s left side to distinguish the field from the parameter.
Show one solution
public class Main {
public static void main(String[] args) {
Goal first = new Goal("Java", 30);
Goal second = new Goal("Reading", 10);
System.out.println(first.describe());
System.out.println(second.describe());
}
}
class Goal {
final String topic;
final int target;
Goal(String topic, int target) {
this.topic = topic;
this.target = target;
}
String describe() {
return topic + ": " + target;
}
}Java: 30
Reading: 10 Change it and explain
Try reversing the new call’s argument order and read the error. Then try assigning first.target = 50 after construction and observe what final protects. Neither rule prevents a caller from passing a negative target initially; that requires validation, which we will add deliberately rather than imply types do it.
Explain why constructors do not return their object with a return expression. The new expression provides the object reference; the constructor’s job is to initialize that object. Keep this distinction separate from an ordinary method that returns an int or String.
Completion is saved in this browser only. It does not measure mastery.