官术网_书友最值得收藏!

Recognizing attributes/fields

We already know the information required for each of the shapes. Now, it is time to design the classes to include the necessary attributes that provide the required data to each instance. In other words, we have to make sure that each class has the necessary variables that encapsulate all the data required by the objects to perform all the tasks.

Let's start with the Square class. It is necessary to know the length of side for each instance of this class, that is, for each square object. Thus, we need an encapsulated variable that allows each instance of this class to specify the value of the length of side.

Tip

The variables defined in a class to encapsulate data for each instance of the class are known as attributes or fields. Each instance has its own independent value for the attributes or fields defined in the class.

The Square class defines a floating point attribute named LengthOfSide whose initial value is equal to 0 for any new instance of the class. After you create an instance of the Square class, it is possible to change the value of the LengthOfSide attribute.

For example, imagine that you create two instances of the Square class. One of the instances is named square1, and the other is square2. The instance names allow you to access the encapsulated data for each object, and therefore, you can use them to change the values of the exposed attributes.

Imagine that our object-oriented programming language uses a dot (.) to allow us to access the attributes of the instances. So, square1.LengthOfSide provides access to the length of side for the Square instance named square1, and square2.LengthOfSide does the same for the Square instance named square2.

You can assign the value 10 to square1.LengthOfSide and 20 to square2.LengthOfSide. This way, each Square instance is going to have a different value for the LengthOfSide attribute.

Now, let's move to the Rectangle class. We can define two floating-point attributes for this class: Width and Height. Their initial values are also going to be 0. Then, you can create two instances of the Rectangle class: rectangle1 and rectangle2.

You can assign the value 10 to rectangle1.Width and 20 to rectangle1.Height. This way, rectangle1 represents a 10 x 20 rectangle. You can assign the value 30 to rectangle2.Width and 50 to rectangle2.Height to make the second Rectangle instance, which represents a 30 x 50 rectangle.

The following table summarizes the floating-point attributes defined for each class:

The following image shows a UML (Unified Modeling Language) diagram with the four classes and their attributes:

主站蜘蛛池模板: 正定县| 黄冈市| 班玛县| 舒城县| 阳信县| 合作市| 什邡市| 东丰县| 郴州市| 阳新县| 巴东县| 望都县| 凤凰县| 大化| 贡觉县| 耒阳市| 庆阳市| 宝鸡市| 缙云县| 苏尼特左旗| 祥云县| 乌拉特后旗| 青川县| 眉山市| 邵东县| 沭阳县| 格尔木市| 井冈山市| 安溪县| 宁乡县| 合阳县| 桐城市| 山西省| 定陶县| 永川市| 浦城县| 衡水市| 新郑市| 根河市| 灵丘县| 海口市|