Skip to content

Inheritance

TheRealMichaelWang edited this page Jun 28, 2021 · 2 revisions

Inheritance

In Minima, records can inherit base records through the extend keyword. Note that unlike Java and C++, Minima does NOT support multi-base inheritance. This practice is done in an effort to discourage constructor-chaining and make your Minima code more extensible/flexible. Ironically, inheritance in Minima is implemented through composition

Note: You should read up on records before reading this page on inheritance.

Inheritance in Action

Copy and paste this code into Minima, it works!

record person {  rem this is the base-class
  name
  age

  proc init(name, age) {
    set this.name to name
    set this.age to age
  }

  proc can_drink {
    return this.age > 21
  }

  proc print {
    extern printl("Name: ", this.name)
    extern printl("Age: ", this.age)
  }
}

record student extends person {  rem this is the derived-class
  grade
  gpa

  proc init(name, age, grade, gpa) {
    goproc init as this.base(name, age)
    set this.grade to grade
    set this.gpa to gpa
  }

  proc is_smart {
    return this.gpa >= 4.0
  }

  proc print {
    goproc print as this.base
    extern printl("Grade: ", this.grade)
    extern printl("GPA: ", this.gpa)
  }
}

set michael to new student("Michael", 15, 9, 4.0)

Using Inhertance

Use the extend keyword to make a derived-record inherit a base-record. A derived-record that inherited a base-record...

  • Inherits the base-records properties. In the example above, michael would also have a name and age property which it inherited from person. However, should student define its own name and age property, it's base class - person's - name and age property would have to be accessed through... *this.base.nameandthis.base.agefrom within one ofstudent's sub-procedure *michael.base.nameandmichael.base.age``` from outside.
  • Inherits the base-records methods. In the example above student inherits all of person's sub-procedures (can_drink, and print). That means you can call goproc can_drink as michael, and it would work - student which is a person - any student object (i.e. michael) can call any procedure defined in student. However, a person object cannot use any of student's sub-procedures because person is NOT a student. Note: that once a class already has a base-class attached to it, it can no longer inherit/extend any more base-classes.

Overriding a Base-Record Sub-Procedure

To override a base-record sub-procedure, simply define a sup-procedure in the derived-class. However, to call a keyword, you must invoke the base record's method through the this.base keyword - which simply gets an instance of the current derived-record as it's base-record's type. In the above example, michael, a student object, calls a person sub-procedure print through the this.base keyword.

Clone this wiki locally