Java Constructors

A constructor is a special method which runs when you create an object with new. It sets the starting values of the object. It has the same name as the class and no return type.

Default constructor

If you do not write any constructor, Java gives your class a default one (with no parameters).

Parameterized constructor

class Student {
    String name;
    int marks;

    Student(String name, int marks) {      // constructor
        this.name = name;                  // this.name is the field, name is the parameter
        this.marks = marks;
    }

    void show() {
        System.out.println(name + ": " + marks);
    }
}

public class Main {
    public static void main(String[] args) {
        Student s = new Student("Riya", 88);
        s.show();
    }
}
Output

Riya: 88

Once you write your own constructor, Java does not make the default one anymore. Then new Student() would not compile:

class Item {
    String name;
    Item(String name) { this.name = name; }
}

public class Missing {
    public static void main(String[] args) {
        Item i = new Item();
    }
}
Output

Missing.java:8: error: constructor Item in class Item cannot be applied to given types;
Item i = new Item();
^
required: String
found: no arguments
reason: actual and formal argument lists differ in length
1 error
error: compilation failed

Constructor overloading

class Book {
    String title;
    String author;
    double price;

    Book() {
        this("Unknown", "Unknown", 0);          // call another constructor
    }

    Book(String title) {
        this(title, "Unknown", 0);
    }

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

    void show() {
        System.out.println(title + " by " + author + ", Rs. " + price);
    }
}

public class Over {
    public static void main(String[] args) {
        new Book().show();
        new Book("Java Basics").show();
        new Book("Java Basics", "R. Sharma", 399.0).show();
    }
}
Output

Unknown by Unknown, Rs. 0.0
Java Basics by Unknown, Rs. 0.0
Java Basics by R. Sharma, Rs. 399.0

this(...) calls another constructor of the same class. It must be the first line, and it saves repeating code.

Copy constructor

class Point {
    int x, y;

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

    Point(Point other) {                // copy constructor
        this.x = other.x;
        this.y = other.y;
    }
}

public class Copy {
    public static void main(String[] args) {
        Point a = new Point(1, 2);
        Point b = new Point(a);
        b.x = 99;
        System.out.println(a.x + " " + b.x);
    }
}
Output

1 99

Order of the work

class Demo {
    int value = 5;                          // field initializer runs first

    {
        System.out.println("Initializer block, value = " + value);
    }

    Demo() {
        System.out.println("Constructor runs");
    }
}

public class Order {
    public static void main(String[] args) {
        new Demo();
    }
}
Output

Initializer block, value = 5
Constructor runs

Rules

  • The name is the same as the class name, and there is no return type (not even void).
  • A constructor can not be static, final or abstract.
  • A constructor can be private, which is used for singletons and utility classes.
Note: Use constructors to make sure that an object is always created in a valid state. Next: Java static and this.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.