Codectionary / Developer documentation / Java

Constructors

A constructor is a special method that runs automatically when an object is created with 'new', typically used to initialize the object's fields. A constructor shares its name with the class and has no return type, not even void. Java supports constructor overloading, letting a class offer multiple ways to construct an object, and constructor chaining with this(...), where one constructor calls another in the same class.

Syntax

public ClassName(parameters) {\n  // initialization code\n}

Examples

Basic Constructor

Initializing fields when an object is created.

public class Point {
    private int x, y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public void display() {
        System.out.println("(" + x + ", " + y + ")");
    }
}

Point p = new Point(3, 4);
p.display();  // (3, 4)

Constructor Overloading

Providing multiple constructors with different parameter lists for flexibility.

public class Rectangle {
    private double width, height;

    public Rectangle() {
        this.width = 1;
        this.height = 1;
    }

    public Rectangle(double side) {  // square shortcut
        this.width = side;
        this.height = side;
    }

    public Rectangle(double width, double height) {
        this.width = width;
        this.height = height;
    }
}

Rectangle r1 = new Rectangle();          // 1x1
Rectangle r2 = new Rectangle(5);          // 5x5 square
Rectangle r3 = new Rectangle(4, 6);       // 4x6

Constructor Chaining with this()

Having one constructor call another in the same class to avoid duplicating initialization logic.

public class User {
    private String name;
    private String role;

    public User(String name) {
        this(name, "member");  // calls the constructor below
    }

    public User(String name, String role) {
        this.name = name;
        this.role = role;
    }

    public void display() {
        System.out.println(name + " (" + role + ")");
    }
}

User u1 = new User("Fola");           // Fola (member)
User u2 = new User("Zain", "admin");   // Zain (admin)

The Default Constructor

Java provides a no-argument constructor automatically, but only if you don't define any constructor yourself.

public class Simple {
    private int value;
    // No constructor written - Java provides a default no-arg one automatically
}

Simple s = new Simple();  // works fine, uses default constructor

public class WithConstructor {
    private int value;

    public WithConstructor(int value) {  // once you write ANY constructor...
        this.value = value;
    }
}

// WithConstructor w = new WithConstructor();  // Error! default constructor no longer exists

Best practices

  • Use this(...) to chain constructors and avoid duplicating initialization logic across multiple overloads
  • Remember that defining any constructor removes the automatically provided no-argument default constructor
  • Validate arguments inside constructors (e.g. throwing an exception for invalid values) to prevent objects from ever existing in an invalid state
  • Keep constructors focused on initialization - avoid putting complex business logic inside them

At a glance

Purpose
General-purpose application development
File extension
.java
Runs in
Java Virtual Machine
Usually used with
JDK and Java libraries

Specifications & further reading

Related Java documentation

Classes
Classes in Java are blueprints for creating objects, defining their properties (fields) and behaviors (methods). Java is a strictly object-oriented language where everything is encapsulated within classes. A class serves as a template that specifies what data an object will store and what operations it can perform.
Interfaces
An interface defines a contract of methods that implementing classes must provide, without specifying how those methods work internally. Unlike a class, an interface cannot be instantiated directly - it only declares what a class can do, not how. A class uses the 'implements' keyword to fulfill an interface's contract, and a single class can implement multiple interfaces, which is Java's way of achieving a form of multiple inheritance.
Abstract Classes
An abstract class is a class that cannot be instantiated directly and may contain both fully implemented methods and abstract methods (declared without a body, which subclasses must implement). Abstract classes sit between interfaces and regular classes: like an interface, they define a contract; like a regular class, they can hold state (fields) and provide shared, already-implemented behavior.
Access Modifiers
Access modifiers control the visibility of classes, fields, and methods from other parts of a program. Java has four levels: public (accessible from anywhere), protected (accessible within the same package and by subclasses), default/package-private (accessible only within the same package, used when no modifier is written), and private (accessible only within the declaring class itself).