我想摆脱测试器类中每个对象的引用,但出现错误。我使用的方法已在注释中提供给我,但不确定它们是否正确。
任何帮助将不胜感激 :)
这是我的代码:
public class Bicycle {
// Instance Variables
private String name; // Owner's name
private int age; // Owner's age
private char gender; // Owner's gender
private static int instanceCounter = 0;
// Default Constructor - doesn't take in values
public Bicycle() {
this("Not Given", 0, 'U');
instanceCounter++;
}
// Parameter constructor
public Bicycle(String name, int age, char gender) {
this.name = name;
this.age = age;
this.gender = gender;
instanceCounter++;
}
// Getter and setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public char getGender() {
return gender;
}
public void setGender(char gender) {
this.gender = gender;
}
public int countInstances(){
return instanceCounter;
}
}
测试人员:
public class BicycleTester {
public static void main(String args[]){
// Instance one
Bicycle bicycle1 = new Bicycle(null, 0, 'U');
bicycle1.setName("John");
System.out.println("Name: " +bicycle1.getName());
bicycle1.setAge(18);
System.out.println("Age: " +bicycle1.getAge());
bicycle1.setGender('M');
System.out.println("Gender: " +bicycle1.getGender());
System.out.println("");
// Instance two
Bicycle bicycle2 = new Bicycle(null, 0, 'U');
bicycle2.setName("Mary");
System.out.println("Name: " +bicycle2.getName());
bicycle2.setAge(23);
System.out.println("Age: " +bicycle2.getAge());
bicycle2.setGender('F');
System.out.println("Gender: " +bicycle2.getGender());
System.out.println("");
// Instance three
Bicycle bicycle3 = new Bicycle(null, 0, 'U');
bicycle3.setName("Billy");
System.out.println("Name: " +bicycle3.getName());
bicycle3.setAge(15);
System.out.println("Age: " +bicycle3.getAge());
bicycle3.setGender('M');
System.out.println("Gender: " +bicycle3.getGender());
System.out.println("");
// Three ways to get rid of object's reference
void go() {
Life bicycle1 = new Life();
}
Life bicycle2 = new Life();
bicycle2 = new Life();
Life bicycle3 = new Life();
bicycle3 = null;
}
}
最佳答案
好吧,女士,让我们再看一遍基础知识。
我们将从对象AKA实例和引用之间的区别开始。Life bicycle2 = new Life();
在这里,bicycle2
是引用,它将在堆栈中。该引用指向通过调用instance
创建的new Life()
。该实例将在堆上
您不能摆脱对象的引用。您可以摆脱一个实例。
只有一种方法可以做到这一点。
将指向实例的引用设置为null
或to some other instance
示例:Life bicycle2 = new Life();
bicycle2 = null;// the instance created above will be eligible for GC
或者您也可以这样做:Life bicycle2 = new Life();
bicycle2 = new Life();
//上面创建的生命实例将被丢弃。
请注意:引用一旦超出范围就会依赖于范围,将无法访问。我不认为您在这里谈论这个话题。