Constructors in Java – Types, Rules and Examples
A constructor is a special block of code that runs when an object is created with new. Its job is to put the new object into a valid, ready-to-use state: set its fields, check the input, and prepare anything else the object needs.
This tutorial explains how constructors work, the different types (default, no-argument, parameterized), overloading and validation, the order in which objects are initialised, and how constructors differ from ordinary methods.
1. What Is a Constructor?
Think of a constructor as the setup step when you buy a new phone: choose the language, sign in, set the time. After that, the phone is ready. Every new Book(...) call runs the Book constructor in the same way.
A constructor:
- Has the same name as the class.
- Has no return type, not even
void. - Runs automatically once, when the object is created.
- Can take parameters and can be overloaded.
- Can have access modifiers (
public,private…) but cannot bestatic,finalorabstract.
2. A Parameterized Constructor
public class ConstructorBasics {
static class Book {
String title;
String author;
double price;
// Parameterized constructor: same name as the class, no return type
Book(String title, String author, double price) {
this.title = title;
this.author = author;
this.price = price;
}
String describe() { return title + " by " + author + " (Rs. " + price + ")"; }
}
public static void main(String[] args) {
Book b1 = new Book("Wings of Fire", "A. P. J. Abdul Kalam", 299);
Book b2 = new Book("The Guide", "R. K. Narayan", 250);
System.out.println(b1.describe());
System.out.println(b2.describe());
}
}
Wings of Fire by A. P. J. Abdul Kalam (Rs. 299.0) The Guide by R. K. Narayan (Rs. 250.0)
Inside the constructor, this.title refers to the field and title to the parameter. Using this. resolves the name clash.
3. Default and No-Argument Constructors
If a class declares no constructor at all, the compiler adds a default constructor: public (or matching the class's access), with no parameters and an empty body. Fields then keep their default values. You can also write your own no-argument constructor to set better starting values:
public class DefaultConstructor {
// No constructor written: the compiler adds "Counter() { }"
static class Counter {
int count; // default value 0
String label; // default value null
}
// A no-argument constructor that sets useful starting values
static class Settings {
String theme;
int fontSize;
Settings() {
theme = "light";
fontSize = 14;
}
}
public static void main(String[] args) {
Counter c = new Counter();
System.out.println("Counter: count=" + c.count + ", label=" + c.label);
Settings s = new Settings();
System.out.println("Settings: theme=" + s.theme + ", fontSize=" + s.fontSize);
}
}
Counter: count=0, label=null Settings: theme=light, fontSize=14
Book only has Book(String, String, double), then new Book() does not compile.4. Types of Constructors
| Type | Description | Example |
|---|---|---|
| Default | Added by the compiler when no constructor is written | (invisible) Counter() { } |
| No-argument | Written by you, takes no parameters | Settings() { theme = "light"; } |
| Parameterized | Takes values to initialise the object | Book(String title, ...) |
| Copy constructor | Creates an object from another object of the same class | Book(Book other) |
| Private constructor | Prevents creation from outside the class | private Config() { } |
5. Constructor Overloading and this(...)
A class can have several constructors with different parameter lists. To avoid repeating code, simpler constructors call a more complete one with this(...), which must be the first statement. This is called constructor chaining.
public class OverloadedConstructors {
static class Pizza {
final String size;
final String crust;
final boolean extraCheese;
Pizza() { this("medium"); } // defaults
Pizza(String size) { this(size, "thin", false); }
Pizza(String size, String crust, boolean extraCheese) { // the "main" constructor
this.size = size;
this.crust = crust;
this.extraCheese = extraCheese;
}
@Override public String toString() {
return size + " " + crust + "-crust pizza" + (extraCheese ? " with extra cheese" : "");
}
}
public static void main(String[] args) {
System.out.println(new Pizza());
System.out.println(new Pizza("large"));
System.out.println(new Pizza("small", "pan", true));
}
}
medium thin-crust pizza large thin-crust pizza small pan-crust pizza with extra cheese
6. Validating Input in Constructors
A constructor is the best place to reject invalid data. If the arguments are wrong, throw an exception and the object is never created, so the rest of your program never sees a half-valid object:
public class ValidatingConstructor {
static class Account {
private final String id;
private double balance;
Account(String id, double openingBalance) {
if (id == null || id.isBlank()) throw new IllegalArgumentException("id is required");
if (openingBalance < 0) throw new IllegalArgumentException("balance cannot be negative");
this.id = id;
this.balance = openingBalance;
}
@Override public String toString() { return id + ": " + balance; }
}
public static void main(String[] args) {
System.out.println(new Account("ACC-1", 500));
try {
new Account("ACC-2", -10);
} catch (IllegalArgumentException e) {
System.out.println("Not created: " + e.getMessage());
}
}
}
ACC-1: 500.0 Not created: balance cannot be negative
7. Initialization Order
When new Car() runs, Java performs these steps in a fixed order:
public class ConstructorOrder {
static class Vehicle {
Vehicle() { System.out.println("1. Vehicle constructor"); }
}
static class Car extends Vehicle {
String model = initModel(); // field initializers run after super()
{ System.out.println("3. Car instance initializer block"); }
Car() {
super(); // always first (added automatically if omitted)
System.out.println("4. Car constructor body, model = " + model);
}
static String initModel() {
System.out.println("2. Car field initializer");
return "Nexon";
}
}
public static void main(String[] args) {
new Car();
}
}
1. Vehicle constructor 2. Car field initializer 3. Car instance initializer block 4. Car constructor body, model = Nexon
- Memory is allocated and all fields get default values.
- The parent constructor runs (
super(), added automatically if you do not write it). - Field initializers and instance initializer blocks run, in the order they appear in the class.
- The rest of the constructor body runs.
Static fields and static blocks run earlier, once, when the class is first loaded.
8. Constructor vs Method
| Constructor | Method |
|---|---|
| Same name as the class | Any name |
| No return type | Must have a return type or void |
Called automatically by new | Called explicitly, any number of times |
| Runs once per object | Can run many times |
| Not inherited | Inherited (unless private) |
Cannot be static, final or abstract | Can be |
9. Constructors in Records
A record gets a canonical constructor automatically. You can add a compact constructor to validate the values without repeating the assignments:
record Temperature(double celsius) {
Temperature {
if (celsius < -273.15) throw new IllegalArgumentException("below absolute zero");
}
}
10. Best Practices
- Leave every object fully initialised and valid when the constructor finishes.
- Validate arguments and fail fast with clear exceptions.
- Keep constructors simple: no heavy work, network calls or long computations.
- Do not call overridable methods from a constructor; the subclass is not ready yet.
- Use
this(...)to avoid duplicated code between overloaded constructors. - With many optional parameters, consider a builder or static factory methods.
11. Summary
- A constructor initialises a new object; it has the class's name and no return type.
- The compiler adds a default constructor only when you write none.
- Constructors can be overloaded and can call each other with
this(...). - The parent constructor always runs first, then field initializers, then the body.
- Validate input in constructors so invalid objects are never created.
Related Tutorials
Reference: Oracle Java Tutorials: Providing Constructors for Your Classes
Frequently Asked Questions (FAQ)
Q1. What is a constructor in Java?
A special block of code with the same name as its class and no return type, which runs automatically when an object is created with new to initialise it.
Q2. What is a default constructor?
A no-argument constructor that the compiler adds automatically when a class declares no constructors. It calls super() and leaves fields at their default values.
Q3. Is a no-argument constructor the same as a default constructor?
Not exactly. The default constructor is generated by the compiler. A no-argument constructor is one you write yourself, possibly with code inside.
Q4. Can a constructor have a return type?
No. If you add a return type, even void, it becomes an ordinary method that happens to have the class's name, and it will not run on new.
Q5. Can a constructor be private?
Yes. A private constructor prevents other classes from creating objects directly. It is used for singletons, utility classes and factory methods.
Q6. Can a constructor be static, final or abstract?
No. Constructors belong to object creation, are not inherited and cannot be overridden, so these modifiers make no sense and are not allowed.
Q7. Are constructors inherited?
No. A subclass does not inherit its parent's constructors, but each subclass constructor must call a parent constructor, explicitly with super(...) or implicitly with super().
Q8. What is constructor overloading?
Having several constructors in one class with different parameter lists, so objects can be created in different ways.
Q9. What is the difference between this() and super()?
this(...) calls another constructor of the same class; super(...) calls a constructor of the parent class. Either must be the first statement, so a constructor can use only one of them.
Q10. Why does new MyClass() fail after I add a constructor?
Once you declare any constructor, the compiler stops generating the default one. Add an explicit no-argument constructor if you still need it.
Q11. Can a constructor call a method?
Yes, but avoid calling methods that subclasses can override, because they would run before the subclass's fields are initialised.
Q12. Can a constructor throw an exception?
Yes. Throwing an exception stops object creation, so no object reference is returned. Checked exceptions must be declared with throws.
Q13. What is the order of initialization in Java?
Static initializers (once per class), then for each object: parent constructor, field initializers and instance blocks in source order, and finally the constructor body.
Q14. Can an abstract class have a constructor?
Yes. It cannot be instantiated directly, but its constructor runs when a concrete subclass is created, initialising the inherited fields.
Q15. Can an interface have a constructor?
No. Interfaces cannot be instantiated and have no instance state to initialise.
Q16. What is a copy constructor?
A constructor that takes an object of the same class and copies its state, such as Book(Book other). See Copy Constructor in Java.
Q17. Can a constructor be synchronized?
No. The object being constructed is not yet visible to other threads, so the modifier is not allowed. Use synchronized blocks inside if you touch shared state.
Q18. What is a compact constructor?
A record constructor written without a parameter list, used to validate or normalise component values; the fields are assigned automatically afterwards.
Q19. How many constructors can a class have?
Any number, as long as each has a different parameter list.
Q20. Is a constructor a method?
No. It looks similar but has no return type, is not inherited, cannot be called like a method, and runs only during object creation.