AvenNova AvenNova - 5 months ago 13
Java Question

Can't access a variable from another class in Java?

I am trying to call on a variable numFriends I created in another class but when I try to do so, it says "numFriends cannot be resolved to a variable". The variable is incremented each time a new friend is added and I want to display that in my Test class. Here's my code:

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 (executable)

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);
}
}

Answer

You need to say Person.numFriends. This is because numFriends is a static member of the Person class, so you need to use the Person class to reference numFriends.

Comments