CodeBlanks Logo Icon CodeBlanks

Default constructor

Learn the compiler-provided default constructor.

Default constructor

If a class has no constructor defined, Java adds a default constructor automatically. This constructor takes no arguments and has an empty body. But once you write at least one constructor, Java no longer adds the default.

Example: class Light { } has no constructor. new Light() still works; Java has added an empty Light() constructor. But if you write class Light { Light(int b) { } }, then new Light() no longer compiles; because you defined a constructor and Java did not add the default. If you need a no-arg constructor, you must write it yourself.

When to write it yourself?

If your class has any constructor and you also want to call it with no arguments, you must write the empty constructor yourself. This enables new ClassName() to work. The empty body can be just { }.

Example: class Lamp { int brightness; Lamp(int b) { brightness = b; } Lamp() { } }. Here two constructors exist. The second has an empty body; it allows new Lamp() calls. This approach enables both parameterized and no-arg instantiation; it adds flexibility.

Practice Add two constructors to Lamp

Define a class named Lamp. Add an int brightness field. Write two constructors: the first is Lamp(int b), assigning brightness = b;; the second is Lamp() with an empty body. In main call both constructors and print the brightness fields on separate lines.

Starter code

Main.java
// Define the Lamp class
// Add two constructors
// Call both in main

Sample solution

Main.java
class Lamp {
    int brightness;
    Lamp(int b) {
        brightness = b;
    }
    Lamp() {
    }
    public static void main(String[] args) {
        Lamp a = new Lamp();
        Lamp b = new Lamp(80);
        System.out.println(a.brightness);
        System.out.println(b.brightness);
    }
}

Expected output

0
80

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What happens when you write a parameterized constructor?

  • Java does not add the default constructor Correct answer
  • Java still adds the default constructor
  • The class does not compile
  • All constructors are deleted

Explanation: Java does not add the default constructor — the no-arg call no longer compiles.

2 Match the default constructor cases

Term Meaning
No constructor Java adds empty one
Constructor exists Java does not add
Manual empty Enables no-arg call
new Light() Default call

3 Complete the empty constructor

Question
class Lamp {
    int brightness;
    Lamp(int b) { brightness = b; }
    ____ { }
}
Answer
class Lamp {
    int brightness;
    Lamp(int b) { brightness = b; }
    Lamp { }
}

Explanation: The empty constructor is also defined with the class name.

All lessons in Intermediate