Class Data and Behaviors
Classes and Objects
As we learned in Introduction to Determining Data Types, data can be broken into two categories:
- primitive data
- reference data
This tutorial dives deeper into reference data by creating our own classes to model objects. A class is like a blueprint for creating objects. The class defines the attributes and behaviors of the object.
- attributes of a class are the data related to the class. Variables are used to store the data.
- behaviors of a class are the actions for the object. Methods are used to define these actions.
An object is an instance of the class where these attributes have defined values.
Abstraction and Classes
Abstraction is a way of reducing complexity of the program by generalizing the details. There are a few different ways that abstraction can be demonstrated when writing classes.
- data abstraction gives data a name that can represent the many concrete values that could be used in the problem. A data abstraction could be a single variable or a collection of variables such as in a class or list of data.
- procedural abstraction provides a name to a process. Programmers can break down larger problems into smaller, more manageable processes or behaviors. These processes are represented by writing methods. Methods can use parameters to generalize the method so that it can be used for a number of different concrete values. Using procedural abstraction allows programmers to make improvements to the inner workings of a method without affecting the rest of the program.
Planning and Diagrams
It can be helpful to make a plan for your class before you implement it. You can use natural langauge or diagrams to plan your classes. The following is a diagram of a Dice class.
Your Turn
|
Grab a Piece of Paper, Let's Try It! |
- Find an object to model. This could be an object from a game or something physical in your environment. If you can't think of something, consider a spinner or playing card.
- What would you name the class?
- What are the attributes for this class? What are the data types of these attributes?
- What behaviors does this class have? Do they return values? Do they take parameters?
- Draw a diagram of this class.
|
Resources