Skip main navigation

How to Design a Class

Barb Ericson explains how to create a class for a number guessing game. The attributes for this class are the random number and the current guess.
6.4
When my kids were little, I often would occupy them by saying, “I’m thinking of a random number from one to a hundred. You guess, and I’ll tell you if you’re too low, too high, or correct.” And we could do that in code as well. So, what would we need to do that? So, whenever you’re thinking of creating code for a class, you wanna think about what are the attributes or the things, the data, that an object of this class needs to keep track of. And the things I said was, “I’m picking a random number from one to a hundred. So there’s my number, and then there’s your guess.”
37.9
And so those are the two attributes that we would be interested in having, or need to have. And then we need to be able to play the game. So, that would be a method or behavior we would expect from the game. So, we would need attributes of the random number that you’ve picked, we could call that num, for example. And then what’s the current guess, we could just call that guess. And then there’d be a play method that’s going to repeat until you get it correct, which would mean a while loop. And where each time that you’re not correct we’re gonna ask the user for input, and then tell them if it’s too high, too low, or correct.
69.2
So, let’s try to write the code for that.

. . . . . . . . . . . . . . . . . .

This video explains how to create a class for a number guessing game. The two attributes for this class would be the random number and the current guess. Objects of this class also require a play method.

This article is from the free online

The Power of Object-Oriented Programming

Created by
FutureLearn - Learning For Life

Our purpose is to transform access to education.

We offer a diverse selection of courses from leading universities and cultural institutions from around the world. These are delivered one step at a time, and are accessible on mobile, tablet and desktop, so you can fit learning around your life.

We believe learning should be an enjoyable, social experience, so our courses offer the opportunity to discuss what you’re learning with others as you go, helping you make fresh discoveries and form new ideas.
You can unlock new opportunities with unlimited access to hundreds of online short courses for a year by subscribing to our Unlimited package. Build your knowledge with top universities and organisations.

Learn more about how FutureLearn is transforming access to education