I've had a good think on Inheritance, polymorphism and a type system. Id be grateful on any comments on the design?
* Inheritance is specialization (Found out this is called conforming-inheritance). You can overload a method, but adding methods not declared in the super-class are marked as private and can only be used internally.
* Only a super-classes methods are accessible to a subclass (all variables are private).
* Invariants of the superclass must still be held, including the post-conditions of the superclasses overloaded method.
* Assignment is covariant, Arguments are conceptually copied by value.
* When a subclass overrides a method, it does not "replace" the superclasses method, but overloads it. The argument types of a the subclasses method must be specified to be contravariant (equal or less specialized type). The subclass method must call the superclass method in order to hold its post-conditions.
* A subclasses overloaded method can also alter the return type, but must be covariant (equal or more specialized type).
* We have two types of methods, Queries (that return something), and Commands (that alter the objects state). Queries do not have post-conditions, so no Super call's are necessary.
* Command methods create a chain of overloaded methods, connected via Super <method> calls.
How subtype-polymorphism is achieved
the argument copies are downcasted (if required), from the assignment covariance rule. if this fails, The process is tried with the superclass method, if that fails the super class above that is tried etc. Until none match and the error is passed back to the calling function.
some examples.
Code: Select all
INTEGER specializes REAL
a := new Integer(2)
b := new Integer(1)
c := new Real(3.14)
d := new String("5")
e := a + b // e type is Integer.
f := a + c // a(Integer +) fails, tries Super method (Real +), Argument is downcasted to Real and succeeds, f type is Real
g := c + a // c(Real +), a is downcasted and treated as a Real, succeeds, g type is Real.
h := a + d // Error, d can not be downcasted to Integer or Real.
Mikey