Classes

Crystal Classes

Defining Crystal Classes

Crystal classes use class with properties and methods.

Introduction to Crystal Classes

In Crystal, classes are a fundamental building block for creating complex data structures and functionality. They allow you to define properties and methods that operate on data encapsulated within objects. This guide will cover the basics of defining and using classes in Crystal, with practical examples to help you understand their application.

Defining a Class in Crystal

To define a class in Crystal, use the class keyword followed by the class name. Class names should be in PascalCase. Inside the class, you can define properties and methods. Here's a simple example:

Creating and Using Objects

Once a class is defined, you can create objects (instances) of that class. Here's how you instantiate a Car object and use its methods:

Understanding Properties and Methods

Properties in Crystal classes are declared using the property keyword, which automatically generates getter and setter methods. Methods are functions defined within a class that can operate on its data. In the Car class example, display_details is a method that accesses the car's properties to return a string.

Class Inheritance

Crystal supports inheritance, allowing a new class to inherit properties and methods from an existing class. This promotes code reuse and logical hierarchy. Use the < symbol to inherit another class:

In this example, ElectricCar inherits from Car and adds an additional property, battery_capacity. The super keyword is used to call the constructor and the method of the superclass.

Conclusion

Crystal classes provide a robust framework for building and organizing code. By encapsulating related data and functions, classes make it easier to model real-world entities and maintain code. Their support for inheritance further enhances their utility, making them a powerful tool in Crystal programming.