[英]How to use same object at different places in a class?
I have written small java code, and want to use same object which I have created in main method in other methods as well in a class. 我已经编写了小的Java代码,并希望使用在主方法中创建的同一对象以及在其他方法中的某个类。 Is there any way ?
有什么办法吗? I dont want to create every time new object in Checklength method just to call digitSum.
我不想每次在Checklength方法中创建新对象只是为了调用digitSum。 I want use same o object created in main method.
我想使用在main方法中创建的相同o对象。
Note: Without changing method properties 注意:不更改方法属性
public class UserMainCode {
public int digitSum(int input1) {
int num = input1;
int sum = 0;
int output = 0;
int length = 0;
while (num > 0) {
sum = sum + num % 10;
num = num / 10;
}
output = sum;
length = Integer.valueOf(Integer.toString(output).length());
Checklength(length, output);
return length;
}
public static void Checklength(int length, int sum) {
if (length > 1) {
UserMainCode b = new UserMainCode();
b.digitSum(sum);
}
else {
System.out.println(sum);
}
}
public static void main(String[] args) {
UserMainCode o = new UserMainCode();
o.digitSum(976592);
}
}
Any ideas ? 有任何想法吗 ?
The thing to do in this situation is to remove static
from the checklength
method. 在这种情况下,要做的是从
checklength
方法中删除static
checklength
。 static
means that the method belongs at the class-level rather than the instance level. static
表示该方法属于类级别而不是实例级别。 If you remove that, checklength
will be back on the instance-level and will be able to call digitSum
on the same instance (which can be explicitly accessed via the keyword this
). 如果删除该
checklength
,则checklength
将返回到实例级别,并且将能够在同一实例上调用digitSum
(可以通过关键字this
显式访问this
)。
public class UserMainCode {
public int digitSum(int input1) {
int num = input1;
int sum = 0;
int output = 0;
int length = 0;
while (num > 0) {
sum = sum + num % 10;
num = num / 10;
}
output = sum;
length = Integer.valueOf(Integer.toString(output).length());
Checklength(length, output);
return length;
}
public void checklength(int length, int sum) {
if (length > 1) {
// deleted instance b - we don't need it
digitSum(sum); // implicitly means this.digitSum(sum);
}
else {
System.out.println(sum);
}
}
}
All of these operations now happen on the instance created in your main method. 现在,所有这些操作都在您的main方法中创建的实例上进行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.