Java tutorialLesson 11 of 18 · tap to see all lessons
Java tutorial · Beginner
Java Constructors: Default, Parameterized, Overloading, and the this Keyword
Use Java constructors to set up objects when they're created: default and no-argument constructors, parameterized constructors, overloading, and this.
- Qyubie Learn Editorial Team
- Published
- 8 min read
Includes 2 quick checks you can do right here.
In the last lesson, every new object started empty, and we filled in its fields one line at a time: s.name = "Ana"; s.score = 88;. Forget a line and the object is left half-made. A constructor fixes this: it runs automatically when the object is created, and sets it up in one step.
By the end of this lesson you will be able to:
- explain what a constructor is and how it differs from a method,
- describe the default constructor and write a no-argument constructor,
- write parameterized constructors and overload them, and
- use
thisfor fields and to call another constructor.
What a constructor is
A constructor looks like a method, with two differences:
- Its name is exactly the class name.
- It has no return type, not even
void.
It runs once, when new creates the object.
class Student {
String name;
int score;
Student(String n, int s) { // a constructor
name = n;
score = s;
}
}
public class Main {
public static void main(String[] args) {
Student a = new Student("Ana", 88); // fields set at creation
Student b = new Student("Ben", 70);
System.out.println(a.name + " " + a.score);
System.out.println(b.name + " " + b.score);
}
}Output:
Ana 88
Ben 70The values in new Student("Ana", 88) are passed to the constructor's parameters, just like a method call.
| Constructor | Method | |
|---|---|---|
| Name | same as the class | any name (camelCase) |
| Return type | none | required (void or a type) |
| When it runs | automatically, once, with new | whenever you call it |
| Purpose | set up a new object | do a task |
The default constructor
If you write no constructor at all, Java adds one for you: the default constructor. It takes no arguments and leaves the fields at their default values. That's why new Student() worked in the previous lesson.
As soon as you write any constructor, Java stops adding the default one:
class Student {
String name;
Student(String n) { name = n; }
}
// new Student(); // error: constructor Student in class Student cannot be applied to given typesIf you still want new Student() to work, write a no-argument constructor yourself.
No-argument constructors
A no-argument constructor can give fields sensible starting values instead of null and 0:
class Account {
String owner;
double balance;
Account() {
owner = "Unassigned";
balance = 0.0;
System.out.println("New account created");
}
}
public class Main {
public static void main(String[] args) {
Account acc = new Account();
System.out.println(acc.owner + ", " + acc.balance);
}
}Output:
New account created
Unassigned, 0.0The this keyword
Inside a constructor or method, this means "the object being created or used right now". Its most common job is to tell a field apart from a parameter with the same name:
class Book {
String title;
double price;
Book(String title, double price) {
this.title = title; // field = parameter
this.price = price;
}
}
public class Main {
public static void main(String[] args) {
Book b = new Book("Java Basics", 450.0);
System.out.println(b.title + " - " + b.price);
}
}Output:
Java Basics - 450.0Without this, writing title = title; would assign the parameter to itself, and the field would stay null. Naming parameters after the fields and using this. is the standard Java style.
Quick check
Constructor overloading
Like methods, a class can have several constructors if their parameter lists differ. Callers choose how much to provide:
class Product {
String name;
double price;
int stock;
Product(String name, double price, int stock) {
this.name = name;
this.price = price;
this.stock = stock;
}
Product(String name, double price) {
this(name, price, 0); // call the 3-parameter constructor
}
Product() {
this("New item", 0.0); // call the 2-parameter constructor
}
void show() {
System.out.println(name + " | " + price + " | stock " + stock);
}
}
public class Main {
public static void main(String[] args) {
new Product("Ballpen", 12.5, 100).show();
new Product("Notebook", 35.0).show();
new Product().show();
}
}Output:
Ballpen | 12.5 | stock 100
Notebook | 35.0 | stock 0
New item | 0.0 | stock 0this(...) calls another constructor of the same class. It keeps the real setup in one place, so the other constructors just fill in default values. The rule: this(...) must be the first statement in the constructor.
Quick check
Putting it together
A constructor can also check its values, so a new object always starts out valid:
class Subject {
String code;
int units;
Subject(String code, int units) {
this.code = code;
if (units < 1 || units > 6) {
System.out.println("Invalid units for " + code + ", using 3");
this.units = 3;
} else {
this.units = units;
}
}
}
public class Main {
public static void main(String[] args) {
Subject s1 = new Subject("CS 122", 3);
Subject s2 = new Subject("PE 2", 10);
System.out.println(s1.code + ": " + s1.units + " units");
System.out.println(s2.code + ": " + s2.units + " units");
}
}Output:
Invalid units for PE 2, using 3
CS 122: 3 units
PE 2: 3 unitsIn lesson 12 you'll make the fields private, so the constructor and setters become the only ways to set them.
Common mistakes
- Adding a return type:
void Student(String n) { ... }is a regular method, not a constructor. It won't run onnew. - Expecting
new Student()to work after writing only a parameterized constructor. Add a no-argument one. name = name;instead ofthis.name = name;.this(...)that isn't the first line of a constructor: compile error.- Arguments in the wrong order:
new Product(12.5, "Ballpen")doesn't match any constructor.
Summary
- A constructor has the class's name and no return type, and it runs once when
newcreates the object. - If you write no constructor, Java provides a default one; writing any constructor removes it.
- Parameterized constructors set fields from arguments, and overloading lets a class offer several ways to create objects.
this.fieldrefers to the current object's field;this(...)calls another constructor and must come first.
Next lesson: encapsulation and access modifiers: protecting an object's data with private, getters, and setters.