管理同一类的多个实例(Java) [英] Managing multiple instances of same class (Java)

查看:237
本文介绍了管理同一类的多个实例(Java)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,我在一个java程序中管理同一个类的多个实例有些麻烦。我创建了一个java类的几个实例,包含几个从类中的整数添加/减去的方法,但是发生的是添加和减少正在所有的实例上完成(见下面的代码)任何管理这些实例的提示是最感谢的。

Hey I'm having some trouble managing multiple instances of the same class in a java program. I've creating a few instances of a java class that contains a few methods that add/subtract from an integer in the class, but what's happening is that the adding and subtracting is being done on all of the instances (see code below), any tips on managing these instances is most appreciated.

Integerclass num1 = new Integerclass();
Integerclass num2 = new Integerclass();
Integerclass num3 = new Integerclass();
num1.assignvalue(3);
num2.assignvalue(5);
num1.addone();
num2.subtractone();
System.out.println(num1.i);
System.out.println(num2.i);

所以,当我尝试从每个实例的整数类打印出整数'i'时会发生什么它们是相同的,即使它们应该是不同的值,因为它们是不同的实例,并且我向它们添加和减去不同的值。

So what happens when I try to print out the integer 'i' from the integer class from each instance they are identical even though they should be different values since they are different instances and I was adding and subtracting different values to them.

推荐答案

让我们一步步完成这一步。

Let's go through this step by step.

Integerclass num1 = new Integerclass();
Integerclass num2 = new Integerclass();

我们有两个新实例: num1 num2

We have two new instances, num1 and num2.

num1.assignvalue(3);

num1 现在是3。 >

num1 is now 3.

num2.assignvalue(5);

num2 现在是5。 >

num2 is now 5.

num1.addone();

num1 现在是4。 >

num1 is now 4.

num2.subtractone();

num2 现在为4。 >

num2 is now 4.

System.out.println(num1.i);
System.out.println(num2.i);

num1 num2 是4,所以这些将打印相同的东西。

Both num1 and num2 are 4 so these will print the same thing.

您的代码似乎很好。如果您不进行完全相同的计算,他们将打印不同的值。

Your code appears to be fine. If you don't do the exact same calculations, they will print differant values.

这篇关于管理同一类的多个实例(Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆