问题和练习的答案:对象

Questions

public class SomethingIsWrong {
    public static void main(String[] args) {
        Rectangle myRect;
        myRect.width = 40;
        myRect.height = 50;
        System.out.println("myRect's area is " + myRect.area());
    }
}

答案 :代码从不创建Rectangle对象。使用此简单程序,编译器会生成错误。但是,在更现实的情况下,myRect可能会在一处(例如在构造函数中)初始化为null,然后再使用。在这种情况下,程序将编译得很好,但是会在运行时生成NullPointerException

...
String[] students = new String[10];
String studentName = "Peter Smith";
students[0] = studentName;
studentName = null;
...

答案 :对students数组有一个引用,而该数组有对字符串Peter Smith的引用。这两个对象都没有资格进行垃圾回收。数组students不具有垃圾回收的资格,因为它对对象studentName具有一个引用,即使该对象已被赋值为null。对象studentName不符合条件,因为students[0]仍引用该对象。

答案 :程序不会显式销毁对象。程序可以将对对象的所有引用都设置为null,以使其有资格进行垃圾回收。但是该程序实际上并没有销毁对象。

Exercises

答案 :请参见SomethingIsRight

public class SomethingIsRight {
    public static void main(String[] args) {
        Rectangle myRect = new Rectangle();
        myRect.width = 40;
        myRect.height = 50;
        System.out.println("myRect's area is " + myRect.area());
    }
}
public class NumberHolder {
    public int anInt;
    public float aFloat;
}

答案 :请参见NumberHolderDisplay

public class NumberHolderDisplay {
    public static void main(String[] args) {
	NumberHolder aNumberHolder = new NumberHolder();
	aNumberHolder.anInt = 1;
	aNumberHolder.aFloat = 2.3f;
	System.out.println(aNumberHolder.anInt);
	System.out.println(aNumberHolder.aFloat);
    }
}
首页