Alex
Alex

Reputation: 1420

How to use an int from another class?

Im trying to use an integer, that Im using in one class and also use the SAME int in a different class. I forgot, what do I have to do for that?

static? implements? extends? what?

Best regards,

For simplicity:

      public class ETBetaActivity extends Activity implements View.OnClickListener {
      public static int anInt = 50;

Another class

            public class GUI extends Activity implements View.OnClickListener {
             public static int anInt_2 = 5+anInt;

Upvotes: 1

Views: 8663

Answers (3)

Aurelian Cotuna
Aurelian Cotuna

Reputation: 3081

static is used to set that value to class, so all objects of the class will have that.

example:

  public class FirstClass
  {
      public static int yourInt;
  }

and you can access it like this: FirstClass.yourInt

You should consider the following example, if you want to avoid static:

public class FirstClass  
{
   private int yourInt;

   public getInt(){return this.yourInt;}
   public setInt(int _int){ this.yourInt = _int}
}

and from all the classes you can use this using getters and setters. Note that if you use 2nd method (with getter and setters ) you will have different values for yourInt, for each object you create, and that value should be set on constructor .

Upvotes: 1

Hunter McMillen
Hunter McMillen

Reputation: 61510

You don't have to implement or extend anything. If you are in the GUI class and want to access ETBetaActivity's anInt field all you need to do is type:

public static int anInt_2 = 5 + ETBetaActivity.anInt; 

Upvotes: 0

prolink007
prolink007

Reputation: 34554

ETBetaActivity.anInt

public class GUI extends Activity implements View.OnClickListener {              
public static int anInt_2 = 5+ETBetaActivity.anInt; 

Or pass it by reference in some setting method in your GUI class.

Only use the first method listed above if those fields are going to be constant. =)

Upvotes: 1

Related Questions