Constructors
Initialise objects properly using constructors - special methods that run when an object is created with new.
Overview
Key Points
- •Constructor name must match the class name exactly
- •No return type (not void) - this distinguishes it from a regular method
- •Runs automatically when new ClassName(args) is called
- •Used to set initial field values and validate inputs
- •You can overload constructors (different parameter lists)
- •this.fieldName refers to the instance field when a parameter has the same name
- •this() calls another constructor in the same class (constructor chaining)
- •If you define no constructor, Java inserts a default no-arg constructor
Examples
Basic constructor vs no constructor
class Dog {
String name;
String breed;
int age;
// Constructor
Dog(String name, String breed, int age) {
this.name = name; // this.name = instance field
this.breed = breed;
this.age = age;
}
void info() {
System.out.println(name + " (" + breed + ", " + age + " yrs)");
}
}
public class Main {
public static void main(String[] args) {
Dog rex = new Dog("Rex", "German Shepherd", 3);
Dog bella = new Dog("Bella", "Labrador", 5);
rex.info(); // Rex (German Shepherd, 3 yrs)
bella.info(); // Bella (Labrador, 5 yrs)
}
}this.name refers to the field; name (without this.) refers to the parameter. this is needed when both have the same name.
Constructor overloading
class Person {
String name;
int age;
String country;
// No-arg constructor - defaults
Person() {
this("Unknown", 0, "Unknown");
}
// Two-arg constructor
Person(String name, int age) {
this(name, age, "Unknown");
}
// Full constructor
Person(String name, int age, String country) {
this.name = name;
this.age = age;
this.country = country;
}
void info() {
System.out.println(name + ", " + age + ", " + country);
}
}
public class Main {
public static void main(String[] args) {
Person p1 = new Person();
Person p2 = new Person("Alice", 28);
Person p3 = new Person("Bob", 32, "Canada");
p1.info(); // Unknown, 0, Unknown
p2.info(); // Alice, 28, Unknown
p3.info(); // Bob, 32, Canada
}
}this(...) calls another constructor. It must be the very first statement in the constructor body.
Static fields - shared across all objects
class Counter {
static int totalCreated = 0; // shared by all instances
int id;
String label;
Counter(String label) {
totalCreated++;
this.id = totalCreated;
this.label = label;
}
void info() {
System.out.println("#" + id + ": " + label);
}
}
public class Main {
public static void main(String[] args) {
Counter a = new Counter("Alpha");
Counter b = new Counter("Beta");
Counter c = new Counter("Gamma");
a.info(); // #1: Alpha
b.info(); // #2: Beta
c.info(); // #3: Gamma
System.out.println("Total: " + Counter.totalCreated); // 3
}
}static fields belong to the class, not individual objects. Access them via the class name: Counter.totalCreated.
Common Mistakes
- Adding a return type to a constructor (even void): `void Dog(...)` makes it a method, not a constructor
- Misspelling the constructor name - it must match the class name exactly, including capitalisation
- Forgetting this. when a parameter shadows an instance field: `name = name` sets the parameter to itself, not the field
- Calling this() after another statement - this() must be the first line of the constructor
Note
Always initialise all fields in the constructor to ensure objects start in a valid state. Rely on overloaded constructors or default values rather than leaving fields uninitialised.
Exercises
Write Java code and click Run to execute it instantly. When your output looks correct, mark as done.
Completed: 0 / 4 exercises
Knowledge Check
Question 1 of 4