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

3.6 Complex Data Types

3.6.1 Reference Data Types

Along with primitive data types, the Java Virtual Machine (JVM) defines data types known as reference data types. Reference types “refer” to variables and, even though Java doesn’t have an explicit pointer type, can be thought of as pointers to the actual value or set of values represented by variables. An object can be “pointed to” by more than one reference. The JVM never addresses objects directly; instead, the JVM operates on the objects’ references.

There are three distinct reference types: class, interface, and array. Reference types can contain references to dynamically created instances of classes, instances, and arrays. References may also contain a special value known as the null reference. The null reference has no type at runtime but may be cast to any reference type. The default value for reference types is null.

引用類型被認為是實際值的指針或變量的指針。一個對象可以擁有多個引用。有三種不同的引用類型:類、接口和數組。引用類型能夠指向動態創建的類實例、接口和數組。

3.6.2 Class Types

Classes refer to data types that define methods and data. Internally, the JVM typically implements a class type object as a set of pointers to methods and data. Variables defining class types can refer only to instances of the class types or to the null reference, as the following snippet demonstrates:

MyObject anObject = new MyObject(); // 合法
MyObject anotherObject = null; // 合法
MyObject stillAnotherObject = 0; // 不合法

3.6.3 Interface Types

An interface acts as a template defining methods that an object must implement in order to be referred to as an instance of the interface. An interface cannot be instantiated. A class can implement multiple interfaces and be referred to by any of the interfaces that it implements. An interface variable can refer only to instances of classes that implement that interface.

接口扮演著方法模板的角色,對象通過引用接口來實現接口中的方法。

For example, assuming we have defined an interface called Comparable and a class called SortItem, which implements Comparable, we can define the following code:

Comparable c = new SortItem();//對象SortItem實現接口Comparable

If the Comparable interface defines one method, public void compare(Comparable item), then the SortItem class must provide an implementation of the compare method, as follows:

public class SortItem implements Comparable {
    public void compare(Comparable item) {
        ...method implementation here
    }
}

接口是定義方法的模板,對象必須執行該方法的目的是引用接口的實例。接口不能實例化。一個類可以實現多個接口,并且可以引用任何被實現的接口。一個接口變量僅引用執行該接口的類的實例。

主站蜘蛛池模板: 余姚市| 婺源县| 凤凰县| 巫溪县| 栾城县| 扬州市| 调兵山市| 鄂伦春自治旗| 罗山县| 鄱阳县| 肇源县| 南丰县| 东港市| 西乌珠穆沁旗| 青河县| 美姑县| 闸北区| 汪清县| 措勤县| 璧山县| 泰安市| 精河县| 镇平县| 怀柔区| 宜黄县| 乃东县| 望奎县| 澄城县| 方正县| 浦江县| 鄱阳县| 新巴尔虎右旗| 临颍县| 常州市| 文成县| 六枝特区| 广平县| 永登县| 永昌县| 百色市| 光泽县|