Reading — step 1 of 3
Inheritance and super
Inheritance & Method Resolution
Inheritance allows a class to reuse methods from another class. The subclass inherits all methods of the superclass and can override any of them.
Syntax
class Animal {
speak() {
print "...";
}
}
class Dog < Animal {
speak() {
print "Woof!";
}
}
Dog().speak(); // "Woof!"
The < operator indicates that Dog inherits from Animal. We chose < because it reads naturally: "Dog is a subtype of Animal."
Method Resolution
When a method is called on an instance:
- Check the instance's class for the method
- If not found, check the superclass
- Continue up the chain until found or error
class Animal { speak() { print "..."; } }
class Dog < Animal { } // no speak() override
Dog().speak(); // calls Animal.speak() → "..."
The super Keyword
super allows a subclass to call the overridden method:
class Dog < Animal {
speak() {
super.speak(); // call Animal.speak()
print "Woof!";
}
}
Dog().speak(); // "..." then "Woof!"
super is resolved lexically — it always refers to the superclass of the class where the method is defined, not the class of the instance. This distinction matters with deep inheritance chains.
Implementation
Inheritance is implemented by copying method references:
class inherits(subclass, superclass):
for name, method in superclass.methods:
if name not in subclass.methods:
subclass.methods[name] = method
This "copy-down" approach is simple and fast. An alternative is method resolution at call time (walking the class hierarchy), which Ruby and Python use for their more dynamic class systems.
super Resolution
super needs its own environment binding. When we call a method, we bind super to the superclass in the method's environment. The resolver treats super like this — it resolves to a specific depth.
How Ruby Does Inheritance
Ruby supports mixins via modules, providing a form of multiple inheritance without the diamond problem. Python uses C3 linearization for its MRO with full multiple inheritance. We keep things simple with single inheritance only, matching Java's class model and Crafting Interpreters.
Your Task
Implement class inheritance with <, method resolution through the superclass chain, and super for calling overridden methods.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…