Chapter 5
Using Classes and Structs

If you’ve done much object-oriented development, you’re familiar with classes. You might also have noticed, though, that the details of classes vary from language to language. In this chapter, you’ll see Crystal’s specific take on classes, and you’ll learn the ins and outs of working with classes. You’ll learn how to construct a class and a struct, how to use inheritance, and how to control visibility of methods. Along the way, you’ll master syntactic details.

In object-oriented code, methods don’t stand alone most of the time: they form the action part of a class, and they’re the only way to interact with objects. You should only find out the data part of an object (its internal state) by using methods. This is also true in Crystal. But, as we saw earlier, methods can also be used standalone or in modules, providing a more functional approach to coding.

You know that everything in Crystal is an object. Each object has a runtime type, which corresponds to the name of its class and responds to certain methods. You also know that during compilation, things can be a bit more complicated: the compile-time type given by typeof determines which code gets generated and protects you from annoying errors.

When performance is a big concern for your project and simpler value types sound appealing, Crystal also offers structs as a possible alternative to classes.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.69.199