Skip to content

SpecificationIX · Objects

9.4

Inheritance and overriding

With Inherits From, a class receives the attributes and methods of another and can change how some of them behave.

Markdown version

9.4.1 How it works

A subclass inherits from a single superclass. Everything the superclass has, the subclass has too, and an object of the subclass works wherever one of the superclass is expected: a Perro is an Animal.

If the subclass declares a method with the same name and signature, it overrides it. Every call uses the method of the object's real class, not that of the variable's type. This is called dispatch.

ProgramA method that changes in the subclass

Class Animal
  Define nombre As String;

  Method Constructor(n As String)
    This.nombre <- n;
  EndMethod

  Method Sonido() As String
    Return "...";
  EndMethod

  Method Presentarse() As String
    Return This.nombre + " dice " + This.Sonido();
  EndMethod
EndClass

Class Perro Inherits From Animal
  Method Constructor(n As String)
    Super.constructor(n);
  EndMethod

  Method Sonido() As String
    Return "guau";
  EndMethod
EndClass

Algorithm Granja
  Define a As Animal <- New Perro("Toby");
  Write a.Presentarse();
  Define b As Animal <- New Animal("Pez");
  Write b.Presentarse();
EndAlgorithm

Output

Toby dice guau
Pez dice ...

The program finishes normally.

Figure 9.4-1.Presentarse lives in Animal, but This.Sonido() looks first in the object's real class: for Toby it finds the one in Perro.

The class Animal with Sonido and Presentarse, and below it Perro, which inherits from Animal and redefines Sonido. The object Toby is a Perro: the search for Sonido starts in Perro.

Super calls the superclass version on the same object. It is only used inside a subclass, followed by a call.

In short

  • Inherits From gives a class everything its superclass has.
  • A method with the same signature overrides; every call uses the real class.
  • Super calls the superclass version.
  • Single inheritance and no signature changes.