java - 如何检索对象
问题描述
在中Class2
,我想检索objects(obj1,2)
在 init 类中传递的方法变量。但我总是0
在Class2
. 请建议如何obj1,2
在Class2
. 谢谢!
public class Class1 {
public int Value;
public void setMethod(int val) {
this.Value = val;
}
public int getMethod() {
return Value;
}
}
//initialization class
import Class1;
public class init {
Class1 obj1 = new Class1();
Class1 obj2 = new Class1();
obj1.setMethod(10);
obj2.setMethod(20);
System.out.println("obj1 value is" + obj1.getMethod()); // it will print 10
System.out.println("obj2 value is" + obj2.getMethod()); // it will print 20
}
//another class where I want my obj1, obj2 method variables to retrieve
import Class1;
private class Class2 {
Class1 obj1 = new Class1();
System.out.println("obj1 value is" + obj1.getMethod()); // it is printing 0
}
解决方案
您正在尝试从init
类中读取对象 1 和 2,但您已经Class1
在Class2
代码中创建了对象。
您的代码中存在编译错误,并且您没有遵循类和方法的正确命名约定。
请参阅下面的代码,您需要使用公共访问修饰符定义三个单独的类。所有对象初始化都可以在类构造函数中完成,或者您可以定义任何公共方法
public class Class1{
public int value;
/*public void setMethod(int val){this.Value=val; -- here variable name is in small letter so compiler error}
public int getMethod(){return Value; -- here variable name is in small letter so compiler error} -- getter setter name is not correct*/
public void setValue(int val) {this.value=val;}
public int getValue(){return this.value;}
}
public class Init{
Class1 obj1 = new Class1();
Class1 obj2 = new Class1();
public Init() {
obj1.setValue(10);
obj2.setValue(20);
System.out.println("obj1 value is"+obj1.getValue()); // it will print 10
System.out.println("obj2 value is"+obj2.getValue()); // it will print 20
}
}
public class Class2{
/* Class1 obj1 = new Class1(); -- here obj1 will not refer to object in Init class
System.out.println("obj1 value is"+obj1.getMethod()); // it is printing 0 */
public static void main(String[] args) {
Init init = new Init();
Class1 obj1 = init.obj1;
System.out.println("obj1 value is"+obj1.getValue());// this will print 10
}
}
推荐阅读
- powershell - 获取邮箱文件夹权限
- node.js - 如何在nodejs中显示来自json文件的图像
- java - 在不使用 O(n²) 时间的情况下检查 8-puzzle 问题的可解性
- html - 在覆盖 Django 模板中使用本地 Chart.js 渲染图表
- log4net - 如果在配置中指定了多个记录器而不仅仅是根设置,log4net 是否会对性能产生影响?
- c# - 将数据表转换为字符串 - 正在生成此错误“字符串”不包含“用户代码”的定义
- typescript - keyof 不提取接口的命名键
- android - 找不到 com.androidx.multidex:multidex:2.0.1
- typescript - 是否可以在打字稿中动态定义类型?
- node.js - 如何为客户端设置谷歌分析 API?