Java中的所有对象都是引用,您可以像指针一样使用它们。
abstract class Animal
{...
}
class Lion extends Animal
{...
}
class Tiger extends Animal
{
public Tiger() {...}
public void growl(){...}
}
Tiger first = null;
Tiger second = new Tiger();
Tiger third;
引用null:
first.growl(); // ERROR, first is null.
third.growl(); // ERROR, third has not been initialized.
混淆问题:
third = new Tiger();
first = third;
失去细胞:
second = third; // Possible ERROR. The old value of second is lost.
你可以通过首先确保没有进一步需要旧值的第二或分配另一个指针的值第二。
first = second;
second = third; //OK
注意,以其他方式给出第二个值(NULL,new …)也是一个潜在的错误,可能导致丢失它指向的对象。
当您调用new并且分配器无法分配所请求的单元时,Java系统将抛出异常(OutOfMemoryError)。这是非常罕见的,通常是由于run-away递归。
注意,从语言的角度来看,将对象放弃到垃圾收集器根本不是错误。它只是程序员需要知道的东西。同一个变量可以指向不同时间的不同对象,并且当没有指针引用它们时,旧值将被回收。但是如果程序的逻辑需要维护至少一个对象的引用,则会导致错误。
新手经常出现以下错误。
Tiger tony = new Tiger();
tony = third; // Error, the new object allocated above is reclaimed.
你可能想说的是:
Tiger tony = null;
tony = third; // OK.
不当铸件:
Lion leo = new Lion();
Tiger tony = (Tiger)leo; // Always illegal and caught by compiler.
Animal whatever = new Lion(); // Legal.
Tiger tony = (Tiger)whatever; // Illegal, just as in previous example.
Lion leo = (Lion)whatever; // Legal, object whatever really is a Lion.
C指针:
void main() {
int* x; // Allocate the pointers x and y
int* y; // (but not the pointees)
x = malloc(sizeof(int)); // Allocate an int pointee,
// and set x to point to it
*x = 42; // Dereference x to store 42 in its pointee
*y = 13; // CRASH -- y does not have a pointee yet
y = x; // Pointer assignment sets y to point to x's pointee
*y = 13; // Dereference y to store 13 in its (shared) pointee
}
Java指针:
class IntObj {
public int value;
}
public class Binky() {
public static void main(String[] args) {
IntObj x; // Allocate the pointers x and y
IntObj y; // (but not the IntObj pointees)
x = new IntObj(); // Allocate an IntObj pointee
// and set x to point to it
x.value = 42; // Dereference x to store 42 in its pointee
y.value = 13; // CRASH -- y does not have a pointee yet
y = x; // Pointer assignment sets y to point to x's pointee
y.value = 13; // Deference y to store 13 in its (shared) pointee
}
}
更新:如在注释中建议的,必须注意C具有指针算术。但是,我们没有在Java。