0

In below example, what is super() in the Person class calling? I understood that super() is used to invoke a constructor of a parent class, but Person is the parent class in this example?

public class Employee extends Person {
    public static void main(String[] args) {
        Person person = new Employee(); // triggers Employee()
    }

    Employee(String s) {
        super(null); // invokes Person's constructor, could be left out if Person had an empty constructor
        System.out.println(s);
    }

    Employee() {
        this("Employee X"); // invokes Employee(String s)
    }
}

public class Person {
    Person(String s) {
        super(); // ?
    }
}
Pieter
  • 69
  • 1
  • 2
  • 2
    All classes extend `Object` implicitly in Java. – JustAnotherDeveloper Aug 06 '21 at 21:32
  • 1
    All classes ultimately extend from `Object`. That said, this "does" nothing. It calls the Object constructor, but that's the one super constructor that already always gets called because it has to be for Java's class hierarchy system to even work. Explicitly putting that `super()` it the Person constructor effectively changes nothing, other than making things look weird =D – Mike 'Pomax' Kamermans Aug 06 '21 at 21:32
  • You are fine to delete that `super()` call as it does nothing of use. – Hovercraft Full Of Eels Aug 06 '21 at 21:33
  • Correction: OK to delete the `super();` in the `Person` constructor, not so the one in the `Employee` constructor, although , likely it should be `super(s);` and the `Person` class should have a name field that is set by its constructor parameter. – Hovercraft Full Of Eels Aug 06 '21 at 21:53

0 Answers0