Classes

Crystal Inheritance

Class Inheritance

Crystal inheritance uses < for single inheritance.

Introduction to Crystal Inheritance

Inheritance is a fundamental concept in object-oriented programming that allows a class to inherit properties and methods from another class. In Crystal, inheritance is single, meaning a class can only inherit from one other class. The syntax for inheritance in Crystal is straightforward and uses the < symbol.

Basic Syntax of Inheritance

In Crystal, you define a class that inherits from another class using the < symbol. Here's a basic example:

Understanding Method Overriding

Method overriding allows a subclass to provide a specific implementation of a method that is already defined in its superclass. In the example above, the speak method in the Dog class overrides the speak method inherited from the Animal class.

Calling Superclass Methods

Sometimes, you might want to call a method from the superclass within the overridden method. This can be done using the super keyword. Here's how you can do it:

Conclusion

Inheritance in Crystal is simple and powerful, allowing you to create a clear and maintainable object-oriented design. By using the < symbol, you can easily establish relationships between classes, enabling method overriding and the use of the super keyword to enhance functionality.

Previous
Structs