From the course: Computer Science Principles: Programming

Make your own classes and objects

From the course: Computer Science Principles: Programming

Start my 1-month free trial

Make your own classes and objects

- There's a lot that goes into building a class. It isn't just building the members of the class, but also about anticipating how you and others will use them. The other fact is while you might know what you intended to do with your classes, someone else might not. So it's important to add in some sort of guidance or rules to your class to make sure that they are used the way you intended. Let's take, for example, a class that defines a review for a movie. Each instance will contain a movie review. So an integer is used to rate a movie on a scale of one to five stars. Seems simple enough, right? You, as the creator of the class, know that a review would be anywhere from zero to five stars. But would someone else? Someone else might think that a movie they absolutely love is worth 10 stars, but that doesn't fit within your class. Here's why. If you create a class and set a property member as an integer, someone can put whatever integer they want: one, five, 10, or even 1,000. There isn't any limit because you haven't provided any guidance or rules for how the property works. If you take a property like rating for the MovieReview class and set it to an integer, you are, by default, making it publicly accessible to anyone. You don't always want to give unrestricted public access to your properties. So you have to be a little bit sneaky. You can take members of a class and make them either private or public. Public means that anyone can access them. They could access public properties like any other variable and public methods like any function. Private members are available only within the instance, and they are hidden from anything outside of the class. So, for our movie rating, we can set that as a private property. But now we have a completely different problem. We can't access the property. Instead, we can create two public methods that will allow us to get the value of the rating and set the value. These are called getter and setter methods. In these methods, we can define our rules that govern the movie ratings. We can accept an integer value and inside of the method, we can see if it's higher than five or less than zero. We can then adjust it if it is out of bounds and then set the private property according to the rules we have defined for the method. Going the other way, we can get a value from another method that returns the value from the private property. Using getters and setters allow you as a programmer to create some rules that govern your class members. Depending on the programming language, there are ways you can disguise getter and setter methods as properties so others that are programming with your classes won't know the difference, and you can still put the rules in place that you need.

Contents