【问题标题】:Can't access a variable from another class in Java?无法从 Java 中的另一个类访问变量?
【发布时间】:2016-10-18 12:52:00
【问题描述】:

我正在尝试调用我在另一个类中创建的变量 numFriends,但是当我尝试这样做时,它显示“numFriends 无法解析为变量”。每次添加新朋友时变量都会增加,我想在我的测试类中显示它。这是我的代码:

一级

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 设为私有并为其添加静态 getter/setter 到您的 Person 类。
  • 以后尝试创建Minimal, Complete, and Verifiable example。这里只有 2 行相关,但我必须使用 Ctrl+F 在您的代码中找到它们。
  • 我怀疑 numFriends 应该是静态的,因为我打赌每个 Person 都应该有自己的 numFriends 字段和值。您需要 1)可能重新考虑您的程序设计,以及 2)打开任何 Java 书籍,因为这个问题是非常基本的 Java,最好通过阅读您的文本或教程来学习。

标签: java variables methods arguments


【解决方案1】:

你需要说Person.numFriends。这是因为 numFriends 是 Person 类的静态成员,所以需要使用 Person 类来引用 numFriends。

【讨论】:

  • 谢谢,这成功了。新手,所以我真的很感谢你们所有人的帮助。
猜你喜欢
  • 1970-01-01
  • 2021-05-20
  • 1970-01-01
  • 1970-01-01
  • 2017-08-18
  • 1970-01-01
  • 2012-05-04
  • 2022-01-24
相关资源
最近更新 更多