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

3.7 Composite Data Types

The Java language does not support structs or unions. Instead, classes or interfaces are used to build composite types. In defense of this limitation, classes provide the means to bundle data and methods together, as well as a way to restrict(限制)access to the private data of the class. For example, using a struct in C, we might define a car this way:

struct Car

{

char*model;

char*make;

int year;

Engine*engine;

Body*body;

Tire**tires;

}

The example above implies that we have previously defined Engine, Body, and Tire structs. In Java, the example above assumes that we have previously defined the CarModels and CarMakes interfaces and that we have previously defined the classes Engine, Body, Tire, DurangoEngine, DurangoBody, and GoodyearTire.

3.7.1 Initializing Composite Data Types

Composite data types are initialized by the code defined in the constructor called when a creation technique, such as “new,” is applied to a variable of a class type. Fields of a class are initialized with their default values or with explicit value assignments before the constructor is called.

復(fù)合數(shù)據(jù)類型的初始化由構(gòu)造方法的代碼實(shí)現(xiàn),構(gòu)造方法是在new創(chuàng)建對(duì)象。

In Listing B, when the instance of myClass is created using the new operator, the constructor, public MyClass( ), is called to allow the class to initialize itself. The initialization process occurs as follows:

(1)The statement “int myInt;” is called and assigns the default value, 0, to myInt.

(2)The statement “AnotherClass anotherClass;” is called and assigns the default value, null, to anotherClass.

(3)The statement within the constructor “myint = 2;” is called and assigns the value 2 to myInt.

3.7.2 Predefined Composite Data Types

Java supplies a vast array of predefined composite data types(預(yù)定義復(fù)合數(shù)據(jù)類型). One of these is the String class belonging to the java.lang package. The String class provides methods to perform a number of commonly used string operations, such as length( ), substring(int beginIndex), toUpperCase( ), toLowerCase( ), equals( ) and others. Another commonly used composite data type Java provides is the Vector class belonging to the java.util package. The Vector class defines methods to perform commonly used operations on an expandable array of objects. Some of these methods are add(int index, Object element), elementAt(int index), isEmpty( ), and remove(int index). These are a small sample of the predefined composite data types that Java supplies. In future articles, we’ll discuss these and other predefined types in detail.

主站蜘蛛池模板: 三门县| 凌海市| 西昌市| 从化市| 横峰县| 五莲县| 泗水县| 鄂伦春自治旗| 潜江市| 蒙山县| 蒲江县| 长垣县| 泰顺县| 兰西县| 高安市| 苏尼特右旗| 湖州市| 靖边县| 黔江区| 黑河市| 葵青区| 南雄市| 米泉市| 凤凰县| 旬阳县| 阜宁县| 雅江县| 怀安县| 扶沟县| 苍溪县| 和顺县| 普定县| 浪卡子县| 福建省| 浦县| 绵阳市| 油尖旺区| 陈巴尔虎旗| 玉树县| 枣强县| 开化县|