3.4 Reference Types
We have now looked at 8 of the 9 data types in Java. The final type is what is known as a reference type. Basically, anything that is not a primitive (an int, a float, etc.) is a reference. That means that arrays are references, as are instances of classes. The notion of a reference is similar to that of a pointer in C++. Let’s say you have created a class called MyClass. When you want to create an instance of that class, you’ll probably want to name it so that you can work with it like any variable. In doing so, the variable that you create does not have the object you’ve created in it. Rather, it has a reference to that object in it. Let’s look at an example and see if we can make this make sense:
1: // 创建一个新的对象 2: MyClass anInstanceOfMyClass = new MyClass();
The variable anInstanceOfMyClass does not really contain an instance of MyClass. Rather, it contains the memory address where that instance really exists. The notion of a reference is very important in Java when it comes to multiple accesses to the same object and parameter passing. For now, it’s sufficient enough to know that when you declare an array or the instance of a class, the variable you store it in is a reference, rather than the object itself.
anInstanceOfMyClass引用包含着被创建对象的内存首地址。