Constructors Basics

Setting Up an Object

A constructor is a special method that runs when an object is created with new. It has the same name as the class and no return type. Use it to give fields their starting values. this.name means "the field of this object" (to tell it apart from the parameter).

Example

public class Main {
    public static void main(String[] args) {
        Product p1 = new Product("Wireless Mouse", 699, 25);
        Product p2 = new Product("USB-C Cable", 299, 0);
        p1.show();
        p2.show();
    }
}

class Product {
    String name;
    double price;
    int stock;

    Product(String name, double price, int stock) {
        this.name = name;
        this.price = price;
        this.stock = stock;
    }

    void show() {
        String status = stock > 0 ? stock + " in stock" : "out of stock";
        System.out.println(name + " - Rs. " + price + " (" + status + ")");
    }
}

Output

Wireless Mouse - Rs. 699.0 (25 in stock)
USB-C Cable - Rs. 299.0 (out of stock)

Default Constructor and toString

Example

If you write no constructor, Java adds an empty default constructor. Overriding toString() controls how an object prints.

public class Main {
    public static void main(String[] args) {
        Book b = new Book("Head First Java", "Kathy Sierra");
        System.out.println(b);           // calls b.toString()
        System.out.println("Reading: " + b);
    }
}

class Book {
    String title;
    String author;

    Book(String title, String author) {
        this.title = title;
        this.author = author;
    }

    @Override
    public String toString() {
        return title + " by " + author;
    }
}

Output

Head First Java by Kathy Sierra
Reading: Head First Java by Kathy Sierra

Note: Without toString(), printing an object shows something like Book@1b6d3586 (class name and a hash code).