What is a constructor?
30 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)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)
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); }}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.namewas forgotten.javacgave no error, and the name prints asnull.
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
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); }}Aarav 85 Priya 72
What this code does
new Student("Aarav", 85)copies"Aarav"intostudentNameand85intostudentMarks; the body then copies them into the fields.- Nobody calls the constructor by name. Each
newruns 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.
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.
Example 3 · Watching the order at new
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); }}Before new Constructor starts: null 0 After new: Aarav 85
What this code does
- The constructor runs at the exact moment
newis reached, between the two prints inmain. - When its body starts, the object already exists with
nulland0. Only then does the body store"Aarav"and85. sgets 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
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(); }}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 methodshow()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 ask.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
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); }}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 errorWhat this code does
- With no real constructor in the class,
javacadded 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. Deletingvoidfixes it.
Example 6 · The void trap that compiles: a silent bug
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); }}Speed: 0 Fan ready Speed: 3
What this code does
new Fan()compiles because of the empty constructorjavacadded. Ourvoid Fan()does not run atnew, sospeedis0.f.Fan()runs it only because it is an ordinary method. Removingvoidmakes 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 5Next step
Check your understanding
12 quick questions