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();
EndAlgorithmOutput
Toby dice guau Pez dice ...
The program finishes normally.
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 Fromgives a class everything its superclass has.- A method with the same signature overrides; every call uses the real class.
Supercalls the superclass version.- Single inheritance and no signature changes.