Applying Inheritance
As in all object-oriented languages and much the same as in Ruby, Crystal provides for single inheritance, indicated by: subclass < superclass. Putting properties and methods common to several classes into a superclass lets them all share functionality. That way, you can use all instance variables and all methods of the superclass in the subclass, including the constructors. You can see this in the following example where PDFDocument inherits initialize, name, and print from Document:
| class Document |
| property name |
| |
| def initialize(@name : String) |
| end |
| |
| def print |
| puts "Hi, I'm printing #{@name}" |
| end |
| end |
| |
| class PDFDocument < Document |
| end |
| |
| doc = ... |
Get Programming Crystal now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.