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
请注意,以其他方式给second赋值(NULL,new …)同样可能引起错误,并可能导致丢失其指向的对象。
OutOfMemoryError当你调用new且分配器无法分配所请求的单元格时,Java系统将引发异常()。这是非常罕见的,通常是由于失控的递归导致的。
请注意,从语言的角度来看,将对象放弃到垃圾回收器根本不是错误。这只是程序员需要注意的事情。相同的变量可以在不同的时间指向不同的对象,并且当没有指针引用它们时,旧值将被回收。但是,如果程序的逻辑要求维护对对象的至少一个引用,则将导致错误。
新手经常会犯以下错误。
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 }}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)