[英]How to use an object of a class in a method of the same class?
My problem is the following : 我的问题如下:
I have 2 classes : MainActivity
and Compartment
. 我有2节课:
MainActivity
和Compartment
。
MainActivity
creates an array myComp[][]
of Compartment
. MainActivity
创建一个数组myComp[][]
的Compartment
。 Compartment
has a static variable called PpN2
, and a public method that calculates PpN2
. Compartment
有一个称为PpN2
的静态变量,以及一个计算PpN2
的公共方法。
This method has to calculate myComp[x][y]
. 此方法必须计算
myComp[x][y]
。 PpN2
which is a function of myComp[x-1][y].PpN2
. PpN2
是myComp[x-1][y].PpN2
。
Question : how can I access myComp[x-1][y].PpN2
in the method that calculates myComp[x][y].PpN2
? 问题:如何在计算
myComp[x][y].PpN2
的方法中访问myComp[x-1][y].PpN2
myComp[x][y].PpN2
?
If it is static variable, you can access using reference (or) using class name. 如果它是静态变量,则可以使用引用(或)使用类名进行访问。
Example: 例:
Compartment.PpN2
Remember because of static variable, myComp[x][y] (or)myComp[x-1][y] references updates same variable. 请记住,由于静态变量,myComp [x] [y](或)myComp [x-1] [y]引用会更新同一变量。
It sounds like you need PpN2
to be an instance variable instead of static, and have MainActivity
pass myComp[x-1][y]
into myComp[x][y].calcPpN2()
or whatever the calc method is called. 听起来您需要
PpN2
作为实例变量而不是静态变量,并使MainActivity
将myComp[x-1][y]
myComp[x][y].calcPpN2()
给myComp[x][y].calcPpN2()
或调用calc方法的任何方法。
Alternatively, you could have Compartment
hold a reference to the previous one that the PpN2
calc depends on, and pass it in during construction. 或者,您可以让
Compartment
保留对PpN2
calc所依赖的前一个引用,并在构建过程PpN2
其传递。
The reason that PpN2
should probably be static is that, being static, its value is shared by all instances of type Compartment
. PpN2
可能应该是静态的,是因为它是静态的,它的值由Compartment
类型的所有实例共享。 As an instance variable, each individual Compartment
object will have its own PpN2
value. 作为实例变量,每个单独的
Compartment
对象将具有其自己的PpN2
值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.