Why can't a constructor use the override keyword in EK9?

← Classes and OOP · Ref: Q775

Constructors are NOT inherited in EK9. Each class defines its own constructors independently. The 'override' keyword means 'I am replacing a method inherited from my parent' — since constructors are never inherited, override is meaningless on them.

WHY CONSTRUCTORS ARE NOT INHERITED

A constructor creates an instance of a specific class. ChildClass() creates a ChildClass, not a ParentClass. There is nothing to override because the parent's constructor belongs to the parent.

CALLING PARENT CONSTRUCTORS

Use super() to call the parent constructor from within your constructor. This is delegation, not overriding:

  ChildClass()
    -> name as String
    super(name)

THIS EXAMPLE

The Animal class has a constructor taking a name. Dog extends Animal and has its own constructor that calls super() to initialise the parent. No override needed.

See Q774 for abstract constructor rules. See Q89 for constructor basics. See Q77 for inheritance.

Example

defines module qa.classesandoop.constructoroverride

  defines class

    Animal as open
      name <- String()

      Animal()
        -> n as String
        name :=: n

      speak()
        <- rtn as String: name

      default operator ?

    Dog extends Animal

      Dog()
        -> n as String
        super(n)

      override speak()
        <- rtn as String: `${super.speak()} says woof`

      default operator ?

  defines program

    ShowAnimals()
      stdout <- Stdout()
      dog <- Dog("Rex")
      if dog?
        stdout.println(dog.speak())

Common mistakes

E07060 — Adding 'override' to a constructor is invalid — constructors are not inherited, so there is nothing to override. Each class defines its own constructors. Use super() to call the parent constructor. See ek9 -h E07060 for details.

Incorrect:

      override Dog()
        -> n as String
        super(n)

Correct:

      Dog()
        -> n as String
        super(n)
Other ways to ask this
  • What triggers E07060 override constructor?
  • Are constructors inherited in EK9?
  • Why does override on a constructor fail?

Coming from another language?

Java: constructors are not inherited, override annotation on constructor is compile error. Python: __init__ can be overridden (it is a regular method). Rust: no constructors to override, new() is a convention. Kotlin: constructors not inherited, override not applicable. Go: no constructors. EK9: constructors not inherited, override keyword rejected with E07060.

Keywords: extend, super, inherited, E07060, parent, override, constructor, child, class