java - 从私有变量中获取属性
问题描述
我创建了 2 个方法。Method1
通过 为变量赋值setter
,method2
通过 a 获取变量的值getter
。
但是,当我调用method2
程序时返回null
或null
. 只能使用私有变量,不要使用public
or 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());
}
}
解决方案
的范围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) {...}
推荐阅读
- javascript - Fullcalendar RRule 重复事件 - 在 timeGridWeek 中呈现错误的结束日期
- python - 1241, '操作数应包含 1 列' pandas to_sql
- keras - 具有缩放目标值的 Keras 回归器 MSE
- django - Django 视图装饰器异常不会阻止视图执行
- android - 上传图像文件的问题反应原生 {"isTrusted": false} - ANDROID
- haskell - 避免捕获的替换函数 - Lambda 演算
- python-2.7 - 我想将多字符串转换为列表列表。列表是一行,值用逗号分隔。这些列表存储在一个大列表中
- printf - gettext-runtime/intl/printf.c 在 gettext-0.20 以后不再导出 libintl_swprintf 了吗?
- .net-core - RedisConnectionException:没有连接处于活动状态/可用于服务此操作
- javascript - Nodejs使用crypto-js加密和解密视频文件