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

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:

主站蜘蛛池模板: 凤翔县| 安泽县| 陈巴尔虎旗| 隆德县| 揭阳市| 南汇区| 钦州市| 马尔康县| 灵寿县| 衢州市| 锡林郭勒盟| 平舆县| 北流市| 北流市| 荔浦县| 北流市| 岳西县| 卢氏县| 谷城县| 莱西市| 民权县| 武汉市| 临汾市| 金阳县| 沙洋县| 驻马店市| 屏南县| 汾阳市| 日喀则市| 石城县| 九龙城区| 河南省| 沭阳县| 长武县| 罗源县| 玉龙| 南充市| 乐平市| 平武县| 滨海县| 措美县|