Constants in classes
📖 Scenario: Imagine you are creating a simple program to manage information about cars. Each car has a brand and a fixed number of wheels. The number of wheels is always the same for all cars, so it makes sense to store it as a constant inside the class.
🎯 Goal: You will create a class called Car with a constant WHEELS set to 4. Then you will create a method to display the number of wheels and the brand of the car.
📋 What You'll Learn
Create a class called
CarInside the class, define a constant
WHEELS with the value 4Add an
initialize method that takes a brand parameter and saves itAdd a method
display_info that prints the brand and the number of wheelsCreate an instance of
Car with brand "Toyota"Call the
display_info method on the instance💡 Why This Matters
🌍 Real World
Constants in classes are useful to store values that do not change, like fixed settings or properties shared by all objects of that class.
💼 Career
Understanding constants in classes helps you write clear and maintainable code, which is important in software development jobs.
Progress0 / 4 steps