首页 > 解决方案 > 从私有变量中获取属性

问题描述

我创建了 2 个方法。Method1通过 为变量赋值settermethod2通过 a 获取变量的值getter

但是,当我调用method2程序时返回nullnull. 只能使用私有变量,不要使用publicor static

有适合我的解决方案或代码示例吗?对不起,我是新手。非常感谢!

class Info {
    private String name;
    private int age;
    public Info() {

    }
    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 class Test {
    public static void main(String[] args) {
        Test test = new Test();
        test.method1();
        test.method2();
    }

    public void method1() {
        Info a = new Info();
        a.setName("John");
        a.setAge(21);
    }

    public void method2() {
        Info a = new Info();
        //I want to print Name and Age values from class Info after method1 set value
        System.out.println("Name: " + a.getName() + " Age: " + a.getAge());
    }
}

标签: java

解决方案


的范围Info a = new Info();仅限于您在其中声明它的方法。考虑将其设为字段。

public class Test {

    private Info a = new Info();

    Test test = new Test();
    test.method1();
    test.method2();
}

  public void method1() {
    a.setName("John");
    a.setAge(21);
  }

  public void method2() {
    System.out.println("Name: "+ a.getName() + " Age: " + a.getAge());
  }
}

或者,您可以创建局部变量,但在方法之间传递它们:

在主要

 Info a = new Info();
 Test test = new Test();
 test.method1(a);
 test.method2(a);

当然,这需要您将方法签名更改为

public void method1(Info a) {...}
public void method2(Info a) {...}

推荐阅读