我想删除测试器类中每个对象的引用,但出现错误。我使用的方法是在笔记中给我的,但不确定它们是否正确。
任何帮助将不胜感激:)
这是我的代码:
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;
}
}
最佳答案
好的,女士,让我们再回顾一下基础知识。
我们将从对象又名实例和引用之间的区别开始。
Life bike2 = new Life();
这里,bicycle2
是一个引用,它将位于堆栈上。该引用指向通过调用 new Life()
创建的实例
。该实例将位于堆
您无法删除对象的引用。您可以删除实例。 只有一种方法可以做到这一点。
- 将指向实例的引用设置为
null
或指向其他实例
示例:Life bike2 = new Life();
bicycle2 = null;//上面创建的实例将有资格进行GC
或者你也可以这样做:
Life bike2 = new Life();
bicycle2 = new Life();
//上面创建的life实例将被丢弃。
请注意:引用范围相关,一旦超出范围,它将无法访问。我认为您不是在这里谈论这个。
关于java - 删除对象的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28988102/