我正在尝试调用我在另一个类中创建的变量numFriends但是当我尝试这样做时,它说" numFriends无法解析为变量"。每次添加新朋友时,变量都会递增,我想在我的Test类中显示该变量。这是我的代码:
CLASS ONE
public class Person {
private String fullName;
private char gender;
private int age;
public static int numFriends = 0;
public Person(String nm, char gen, int a) {
fullName = nm;
gender = gen;
age = a;
numFriends++;
}
public void setName(String nm) {
fullName = nm;
}
public void setAge(int a) {
age = a;
}
public int getAge() {
return age;
}
public void setGender(char g) {
gender = g;
}
public String toString() {
return (fullName + ", gender = " + gender + ", age = " + age );
}
}
CLASS TWO(可执行文件)
public class TestPerson {
public static void main(String[] args) {
System.out.println(numFriends + " people at first");
Person p1 = new Person("Otto Mattik", 'M', 22);
p1.setName("Otto Mattik");
p1.setGender('M');
p1.setAge(22);
System.out.println("Person Full Name = " + p1);
Person p2 = new Person("Anna Bollick", 'F', 19);
p2.setName("Anna Bollick");
p2.setGender('F');
p2.setAge(19);
System.out.println("Person Full Name = " + p2);
Person p3 = new Person("Dick Tator", 'M', 33);
p3.setName("Dick Tator");
p3.setGender('M');
p3.setAge(33);
System.out.println("Person Full Name = " + p3);
changeName(p2, "Anna Bollik-Mattik");
Person[] people = {
p1, p2, p3
};
agePersons(people, 5);
System.out.println("\n" + numFriends + " people after 5 years");
for (Person person : people)
System.out.println("Person fullName: " + person);
}
public static void changeName(Person p, String name) {
p.setName(name);
}
public static void agePersons(Person[] people, int years) {
for (Person person : people)
person.setAge(person.getAge() + years);
}
}
答案 0 :(得分:3)
你需要说Person.numFriends
。这是因为numFriends是Person类的静态成员,因此您需要使用Person类来引用numFriends。