Skip to lesson

What is a constructor?

A constructor is a block of code in a class that runs by itself when new creates an object. Its job is to give the new object its starting values, so the object is ready to use from its very first line.

The problem: setting fields one by one

In Create objects with new (opens in a new tab), every field was set on its own line after new. Forget one line and Java says nothing: the field keeps its default value, and null prints where a name should be.

Example 1 · Setting fields one by one (and forgetting one)

OneByOneDemo.javaJava
class Student {    String name;    int marks;}
public class OneByOneDemo {    public static void main(String[] args) {        Student s1 = new Student();        s1.name = "Aarav";        s1.marks = 85;
        Student s2 = new Student();        s2.marks = 72;          // forgot s2.name
        System.out.println(s1.name + " " + s1.marks);        System.out.println(s2.name + " " + s2.marks);    }}
Output
Aarav 85
null 72

What this code does

  • Without a constructor, every field needs its own line after new, and every new field adds one more line per student.
  • The line for s2.name was forgotten. javac gave no error, and the name prints as null.

A constructor fixes both problems. The caller passes every value inside new, as in new Student("Aarav", 85), and the constructor stores them in the fields, so none can be skipped.

Writing a constructor

A constructor is a special block of code with the same name as its class and no return type. It runs automatically when an object is created with new, and it gives the new object its starting values.

It looks like a method with two differences: its name is exactly the class name, and it has no return type, not even void. The values inside new Student("Aarav", 85) go into its parameters.

Example 2 · A constructor that sets the fields

SetFieldsDemo.javaJava
class Student {    String name;    int marks;
    Student(String studentName, int studentMarks) {   // class name, no return type        name = studentName;        marks = studentMarks;    }}
public class SetFieldsDemo {    public static void main(String[] args) {        Student s1 = new Student("Aarav", 85);        Student s2 = new Student("Priya", 72);        System.out.println(s1.name + " " + s1.marks);        System.out.println(s2.name + " " + s2.marks);    }}
Output
Aarav 85
Priya 72

What this code does

  • new Student("Aarav", 85) copies "Aarav" into studentName and 85 into studentMarks; the body then copies them into the fields.
  • Nobody calls the constructor by name. Each new runs it once, for its own object, so each student is complete in one line.

The parameters are local variables of the constructor, as in Parameters and arguments (opens in a new tab): they disappear when it ends, while the fields keep the values. The parameter names differ from the field names on purpose; The this keyword (opens in a new tab) shows how to use the same names.

The name must match the class exactly, with the same capital letters: Student(...), not student(...).

What happens at new, step by step

new Student("Aarav", 85) does three things, always in this order. Java first makes the object, with every field at its default value; then the constructor body runs; then new hands back the reference.

new Student("Aarav", 85) in three steps. Step 1: Java makes the object and its fields hold the defaults name = null and marks = 0. Step 2: the constructor body stores "Aarav" and 85. Step 3: new hands back the reference, and s points to the finished object.

Example 3 · Watching the order at new

NewStepsDemo.javaJava
class Student {    String name;    int marks;
    Student(String studentName, int studentMarks) {        System.out.println("Constructor starts: " + name + " " + marks);        name = studentName;        marks = studentMarks;    }}
public class NewStepsDemo {    public static void main(String[] args) {        System.out.println("Before new");        Student s = new Student("Aarav", 85);        System.out.println("After new: " + s.name + " " + s.marks);    }}
Output
Before new
Constructor starts: null 0
After new: Aarav 85

What this code does

  • The constructor runs at the exact moment new is reached, between the two prints in main.
  • When its body starts, the object already exists with null and 0. Only then does the body store "Aarav" and 85.
  • s gets the reference last, after the constructor has finished.

The constructor runs exactly once per object, at new. Copying a reference, Student t = s;, makes no new object, so no constructor runs. To change an object later, call a method on it.

Constructor vs method

A report card is filled in once, when the student joins, but printed many times. A constructor is that one-time set-up step at new; a method is an action you can call again and again.

Example 4 · A constructor that works things out

MarksheetDemo.javaJava
class Marksheet {    String name;    int total;    String result;
    Marksheet(String studentName, int maths, int physics, int chemistry) {        name = studentName;        total = maths + physics + chemistry;        if (maths >= 35 && physics >= 35 && chemistry >= 35) {            result = "Pass";        } else {            result = "Fail";        }    }
    void show() {        System.out.println(name + ": " + total + " " + result);    }}
public class MarksheetDemo {    public static void main(String[] args) {        Marksheet k = new Marksheet("Kavya", 88, 79, 91);        Marksheet r = new Marksheet("Rohan", 62, 30, 70);        k.show();        r.show();        k.show();    }}
Output
Kavya: 258 Pass
Rohan: 162 Fail
Kavya: 258 Pass

What this code does

  • A constructor is not only for copying values: this one adds the marks and decides the result, once for each object.
  • The constructor ran twice, once per new. The method show() ran three times, once per call.

The differences in one place:

  • Name: a constructor has the class name; a method has any name, usually a verb like show.
  • Return type: a constructor has none; a method always has one (void, int, String…).
  • When it runs: a constructor once, at new; a method on every call, such as k.show().

The void trap

void Student(String studentName, int studentMarks) looks like a constructor, but void makes it an ordinary method that happens to have the class name. The class then has no constructor of its own, and the error shows up at new.

Example 5 · The void trap: a confusing compile error

VoidDemo.javaJava
class Student {    String name;    int marks;
    void Student(String studentName, int studentMarks) {        name = studentName;        marks = studentMarks;    }}
public class VoidDemo {    public static void main(String[] args) {        Student s = new Student("Aarav", 85);        System.out.println(s.name + " " + s.marks);    }}
Sample compiler output
VoidDemo.java:13: error: constructor Student in class Student cannot be applied to given types;
        Student s = new Student("Aarav", 85);
                    ^
  required: no arguments
  found:    String,int
  reason: actual and formal argument lists differ in length
1 error

What this code does

  • With no real constructor in the class, javac added an empty one with no parameters. The default constructor (opens in a new tab) explains why.
  • So new Student("Aarav", 85) finds only a constructor that wants nothing: required: no arguments. Deleting void fixes it.

Example 6 · The void trap that compiles: a silent bug

SilentVoidDemo.javaJava
class Fan {    int speed;
    void Fan() {        speed = 3;        System.out.println("Fan ready");    }}
public class SilentVoidDemo {    public static void main(String[] args) {        Fan f = new Fan();        System.out.println("Speed: " + f.speed);        f.Fan();        System.out.println("Speed: " + f.speed);    }}
Output
Speed: 0
Fan ready
Speed: 3

What this code does

  • new Fan() compiles because of the empty constructor javac added. Our void Fan() does not run at new, so speed is 0.
  • f.Fan() runs it only because it is an ordinary method. Removing void makes it a real constructor again.

When javac says required: no arguments but you wrote a constructor with parameters, look for void (or any other return type) before its name.

Find the bug

Find the constructor mistake

Select the line that is wrong.

This should create a phone with the brand Nokia.

Round 1 of 5

Next step

Check your understanding

12 quick questions