[英]Can't access a variable from another class in Java?
我试图调用在另一个类中创建的变量numFriends,但是当我尝试这样做时,它显示“ numFriends无法解析为变量”。 每次添加新朋友时该变量都会增加,我想在Test类中显示该变量。 这是我的代码:
第一类
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 );
}
}
第二类(可执行)
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);
}
}
您需要说出Person.numFriends
。 这是因为numFriends是Person类的静态成员,因此您需要使用Person类来引用numFriends。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.