By WebNest Studio Engineering Team
Java - Core Tutorial
Constructors and Constructor Overloading
A constructor is a special block of code that runs automatically when an object is created with new, and its job is to initialize the object's instance variables into a valid starting state. A constructor looks similar to a method but has two defining differences: it has no return type at all — not even void — and its name must exactly match the class name.
Why it matters
A constructor is the one place where you can guarantee that an object starts in a valid state. Knowing when Java supplies a default constructor — and when it silently stops doing so — explains a compile error that puzzles most people the first time they add a constructor with parameters.
Watch: Java Constructors and Overloading
A walkthrough of Java constructors: how they initialise a new object, and how overloading lets one class offer several ways to create it.
Default Constructor
If a class defines no constructor at all, the Java compiler automatically inserts a no-argument default constructor that takes no parameters and initializes fields to their default values (0, false, null). As soon as you write even one constructor of your own, however, the compiler stops providing the default one — if you still need a no-argument constructor at that point, you must write it explicitly.
Constructor Overloading
Just like methods, a class can define multiple constructors as long as their parameter lists differ, which is called constructor overloading. This lets client code create objects in different ways depending on what information is available at that moment — for example, creating an object with default values, or with fully specified values.
Constructor Chaining with this()
Inside one constructor, you can call another constructor of the same class using this(...) with matching arguments. This is called constructor chaining, and it lets you centralize common initialization logic in one constructor instead of duplicating it across several. A constructor can make at most one such call. Until Java 24 it had to be the very first statement. Since Java 25 (flexible constructor bodies), statements may come before it, but only ones that do not use the object being built: they cannot use this, read its fields or call its instance methods.
- Constructor name must exactly match the class name, with matching capitalization.
- Constructors never declare a return type, including
void. - A constructor can call
this(...)orsuper(...)once at most; code before that call must not touch the object being built. - A class loses its free compiler-provided default constructor once any constructor is written explicitly.
Parameterized Constructors and this.field
A parameterized constructor takes the starting values as arguments, so an object is complete the moment it is created. Parameters are usually given the same names as the fields they fill, which hides the fields inside the constructor. Writing this.name = name tells Java to assign the parameter name to the field name of the object being created. Without this., name = name just assigns the parameter to itself and the field keeps its default value.
Validating Arguments in the Constructor
Because every object passes through a constructor, it is the best place to reject bad data. Check the arguments and throw an IllegalArgumentException (or NullPointerException via Objects.requireNonNull) if they make no sense. A caller then can never hold a half-valid object, such as a bank account with a negative balance or a person without a name.
Copy Constructors
A copy constructor takes another object of the same class and copies its values, as in Book(Book other). Java does not generate one for you, but it is a common and readable way to duplicate an object. Copying a field that refers to a mutable object (such as a list) copies only the reference, so for an independent copy, create a new list from the original.
Private Constructors
A constructor can be private, which stops other classes from calling new on it. This is used for utility classes that only hold static methods (like java.lang.Math), and for classes that control how instances are made through a static factory method such as of(...).
Constructors vs Methods
The two look alike, but they play different roles:
- A constructor runs automatically, once per object, when you use
new. A method runs only when you call it, as many times as you like. - A constructor has the class name and no return type. A method can have any name and must declare a return type (or
void). - Constructors are not inherited, although a subclass calls a superclass constructor with
super(...). Methods are inherited and can be overridden.
Examples
Overloaded constructors chained together with this()
public class Rectangle {
int width;
int height;
Rectangle() {
this(1, 1); // chains to the two-argument constructor
}
Rectangle(int side) {
this(side, side); // a square, chains to the two-argument constructor
}
Rectangle(int width, int height) {
this.width = width;
this.height = height;
}
int area() {
return width * height;
}
public static void main(String[] args) {
Rectangle r1 = new Rectangle();
Rectangle r2 = new Rectangle(5);
Rectangle r3 = new Rectangle(4, 6);
System.out.println(r1.area());
System.out.println(r2.area());
System.out.println(r3.area());
}
}
1
25
24
this.field assignment, argument validation and a copy constructor
class Book {
String title;
int pages;
Book(String title, int pages) {
if (pages <= 0) {
throw new IllegalArgumentException("pages must be positive: " + pages);
}
this.title = title; // this.title is the field, title is the parameter
this.pages = pages;
}
Book(Book other) { // copy constructor
this(other.title, other.pages);
}
}
public class BookDemo {
public static void main(String[] args) {
Book original = new Book("Java Basics", 320);
Book copy = new Book(original);
copy.title = "Java Basics, 2nd Edition";
System.out.println(original.title + " (" + original.pages + " pages)");
System.out.println(copy.title + " (" + copy.pages + " pages)");
try {
new Book("Empty", 0);
} catch (IllegalArgumentException e) {
System.out.println("Rejected: " + e.getMessage());
}
}
}
Java Basics (320 pages)
Java Basics, 2nd Edition (320 pages)
Rejected: pages must be positive: 0
Common Mistakes
- Accidentally giving a constructor a return type like "void", which turns it into a regular method that must be called explicitly rather than a constructor invoked by "new".
- Writing a custom constructor and then being surprised that "new MyClass()" no longer compiles, because defining any constructor removes the automatic default one.
- Using this or reading a field before the this(...) call. Since Java 25 statements may come before it, but they must not touch the object being built (and before Java 25 nothing at all could come first).
- Confusing this(...) (calls another constructor of the same class) with super(...) (calls a constructor of the parent class).
- Writing "name = name;" in a constructor instead of "this.name = name;", which assigns the parameter to itself and leaves the field at its default value.
Exercise
Give Point two constructors: one that takes x and y, and a no-argument one that creates the origin by calling the other with this(0, 0).
Expected output: (0, 0) then (3, 4)
class Point {
int x;
int y;
// TODO: Point(int x, int y)
// TODO: Point() that reuses the constructor above
String describe() {
return "(" + x + ", " + y + ")";
}
}
public class PointDemo {
public static void main(String[] args) {
System.out.println(new Point().describe());
System.out.println(new Point(3, 4).describe());
}
}
Show hints
- Use
this.x = x;to assign the parameter to the field with the same name. - The no-argument constructor only needs one statement:
this(0, 0);.
Show solution
class Point {
int x;
int y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
Point() {
this(0, 0);
}
String describe() {
return "(" + x + ", " + y + ")";
}
}
public class PointDemo {
public static void main(String[] args) {
System.out.println(new Point().describe()); // (0, 0)
System.out.println(new Point(3, 4).describe()); // (3, 4)
}
}
Quick quiz
1. A class declares only Point(int x, int y). What happens with new Point()?
- A. It creates a Point at 0, 0
- B. It does not compile
- C. It throws an exception at runtime
- D. It calls the two-argument constructor with nulls
Show answer
B. The compiler adds a default no-argument constructor only when the class declares no constructors at all.
2. What is the return type of a constructor?
- A. void
- B. The class type
- C. It has no return type
- D. Object
Show answer
C. A constructor declares no return type, not even void. Adding one turns it into an ordinary method.
3. In Java 25, what may come before a call to this(...) inside a constructor?
- A. Any code at all
- B. Only statements that do not use the object being created
- C. Nothing: it must always be the first statement
- D. Only a return statement
Show answer
B. Since Java 25, a constructor can run statements such as argument checks before this(...), but that code cannot use this, read fields or call instance methods. Before Java 25, this(...) had to be the first statement.
Interview questions
What is the difference between a default constructor and a no-argument constructor?
Show answer
A default constructor is the one the compiler generates when a class declares no constructor. It takes no arguments and does nothing beyond calling the superclass constructor. A no-argument constructor is any constructor with an empty parameter list, including one you write yourself. Once you write any constructor, the compiler no longer provides a default one.
Can a constructor be private? Why would you do that?
Show answer
Yes. A private constructor prevents other classes from creating instances with new. It is used for the singleton pattern, for classes that hand out instances through static factory methods, and for utility classes that contain only static methods and should never be instantiated.
Key Points to Remember
- A constructor has the same name as the class and no return type, not even void.
- The compiler supplies a default no-argument constructor only if you define no constructor yourself.
- Constructors can be overloaded like methods, differing by parameter list.
- this(...) chains to another constructor in the same class; code before it must not use the object being built.
- Validate arguments in the constructor so no object can exist in an invalid state.
Practice in the playground
Write and run your own code for this topic, or start from the exercise or an example. Runs plain Java 17. Frameworks such as Spring, and databases, are not available here. Your code for each topic is kept in this browser.
Run the examples
Change an input, predict the result, then compare it with the output. Explain why the result changes.
Written by
WebNest Studio Engineering Team
Practical lessons from developers working with Java, Python, React, databases and production systems.
Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering