【发布时间】:2015-03-11 13:36:58
【问题描述】:
我想在我的测试器类中删除每个对象的引用,但我遇到了错误。我正在使用的方法已在注释中提供给我,但不确定它们是否正确。
任何帮助将不胜感激:)
这是我的代码:
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;
}
}
【问题讨论】:
-
请发布错误以及“摆脱对象引用”的含义。你的意思是你想让它有资格进行垃圾收集吗?
-
@MarcusWidegren 是的,这就是我想要的
标签: java variables object reference instance