Java
Summary - Constructor
Combine parameterized constructors and this() to write a Product class.
Summary - Constructors
In this group you learned constructor basics, parameterized constructors, overloading, chaining with this() and default constructors. A constructor gives an instance its initial values when it is created; its name matches the class name and it has no return type.
Now you will bring it all together: define a class, add multiple constructors, chain with this() and print instances. Constructors provide a clean start in object-oriented design; they reduce manual field assignment.
Exercise Define the Timer class
Define a class named Timer. Add an int seconds field. Write two constructors: the first is Timer(int s), assigning seconds = s;; the second is Timer(), calling the first with this(60). In main call both constructors and print the seconds fields on separate lines.
Show example solution
class Timer {
int seconds;
Timer(int s) {
seconds = s;
}
Timer() {
this(60);
}
public static void main(String[] args) {
Timer a = new Timer();
Timer b = new Timer(30);
System.out.println(a.seconds);
System.out.println(b.seconds);
}
}
What comes next?
You learned constructors. In the next groups you will share code between classes with inheritance, call the superclass constructor with super and override methods. These are the foundations of class hierarchies.
This group combined constructor definition, parameterized calls, overloading and this() chaining. These are the basics of object creation. Next you will build relationships between classes with inheritance; you will pass a superclass's fields and methods down to subclasses.
Exercise Define the Counter class
Define a class named Counter. Add an int count field. Write two constructors: the first is Counter(int c), assigning count = c;; the second is Counter(), calling the first with this(0). Add a public String toString() method returning "Count: " + count. In main call both constructors and print each instance with println.
Show example solution
class Counter {
int count;
Counter(int c) {
count = c;
}
Counter() {
this(0);
}
public String toString() {
return "Count: " + count;
}
public static void main(String[] args) {
Counter a = new Counter();
Counter b = new Counter(5);
System.out.println(a);
System.out.println(b);
}
}
Test yourself
-
What happens if no constructor is defined in a class?
- A compile error occurs
- Java adds an empty default constructor
- The class does not run
- All fields are deleted
Show answer
Java adds an empty default constructor — Java adds an empty default constructor — the new call works.
-
Complete the this() call
class Timer {
int seconds;
Timer(int s) { seconds = s; }
Timer() {
____(60);
}
}
Show answer
class Timer {
int seconds;
Timer(int s) { seconds = s; }
Timer() {
this(60);
}
}
Next lesson: extends