简体   繁体   English

如何在同一个类的方法中使用一个类的对象?

[英]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节课: MainActivityCompartment

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 . PpN2myComp[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作为实例变量而不是静态变量,并使MainActivitymyComp[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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM