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

Reach your personal and professional goals

Unlock access to hundreds of expert online courses and degrees from top universities and educators to gain accredited qualifications and professional CV-building certificates.

Join over 18 million learners to launch, switch or build upon your career, all at your own pace, across a wide range of topic areas.

Start Learning now