How do you pass variables between classes?


Last Updated:

  1. deenybird

    deenybird New Member This Topic's Starter

    Joined:
    Feb 4, 2009
    Messages:
    3
    Likes Received:
    0
    What intents do I use to pass a variable to another class? And also which intent do I use to receive it?
    thanks
     

    Advertisement
  2. GiantKruemel

    GiantKruemel Member

    Joined:
    Feb 13, 2009
    Messages:
    6
    Likes Received:
    0
    Why per Intents?
    You can pass variables by creating an objekt of another class...
    Like here:

    public class Main {

    static Test t = new Test();
    public static void main(String[] args){
    t.Set(3);
    System.out.println(t.Get());
    }

    }

    extra file:

    class Test{
    private int i;
    public int Get(){
    return i;
    }
    public void Set( int a ){
    this.i = a;
    }
    }

    I hope that helps

    BTW: There is no main in android, so just do this without an main...
    in any class you wish...

    MFG Da Wolf
     
  3. Sam Voss

    Sam Voss Well-Known Member

    Joined:
    Jun 25, 2010
    Messages:
    367
    Likes Received:
    44
    check out this I had a question on this, and posted the Idea I had, so if it comes to be its a good idea, or you try it out, let me know what you think, hopefully by tomorrow someone'll tell me if i have an obvious flaw in this idea
     
  4. Extodus

    Extodus Active Member

    Joined:
    Feb 15, 2010
    Messages:
    41
    Likes Received:
    2
    To pass variables between classes you use getters and setters.

    Examples
    Code (Text):
    1. class Rectangle {
    2.   int x;
    3.   int y;
    4.   int width;
    5.   int height;
    6.  
    7.   public int getX() {
    8.     return this.x;
    9.   }
    10.  
    11.   public int getY() {
    12.     return this.y;
    13.   }
    14.  
    15.   public int setX(int x) {
    16.     this.x = x;
    17.   }
    18.  
    19.   public int setY(int y) {
    20.     this.y = y;
    21.   }
    22.  
    23.   // etc etc
    24. }
    25.  
    26. // In another class you'd have:
    27.  
    28. Rectangle r1;
    29.  
    30. r1.setX(50);
    31.  
    32. int example = r1.getX();
    33.  
     

Share This Page

Loading...