Java - What is wrong: super default constructor

Question

What is wrong with the following code?

class Employee {
  private String name = "Unknown";

  public Employee(String name) {
    this.name = name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getName() {
    return name;
  }
}
public class Manager extends Employee {
  // No code for now
}


Click to view the answer

// Won't compile
public class Manager extends Employee {
  // No code for now
}

Note

It generates the following compiler error: constructor Employee() not found in class Employee.

You have not added any constructor for the Manager class.

The compiler will add a no-args constructor for it.

It will try to inject a super() call as the first statement inside the no-args constructor, which will call the no-args constructor of the Employee class.

However, the Employee class does not have a no-args constructor.

To fix the error

You can add a no-args constructor to the Employee class, like so:

public class Employee {
        // A no-args constructor
        public Employee() {
        }
        /* All other code for class remains the same */
}

Or you can add a no-args constructor to the Manager class and explicitly call the constructor of the Employee class with a String argument as

public class Manager extends Employee {
        public Manager() {
                // Call constructor of Employee class explicitly
                super("Unknown");
        }
}