sharing variables between classes

edited October 2013 in How To...

hi, how to share variables between classes without making them global? like for example there is class Ball and class Whatever.

Ball has x, y and they are connected to mouse x= MouseX; y=MouseY;

Whatever also has variables related to x, y and i would like to connect those with Ball's x, y not using mouse anymore what is the correct syntax for that without making both classes into one or making those variables global? there was a way i think, something like x=Whatever(x); y=Whatever(y);

possible? i don't have code, hope i make the problem clear enough

Answers

  • Answer ✓

    Is this what you mean

    public class Ball {
        private float x,y;
    
       public Ball(float x, float y){
            this.x = x;
            this.y = y;
        }
    
        public float getX(){
            return x;
        }
    
        public void setX(int x){
            this.x = x;
        }
    
        public float getY(){
            return y;
        }
    
        public void setY(int y){
            this.y = y;
        }
    }
    

    then

    Ball ball = new Ball(0,0);
    
    ball.setX(mouseX);
    ball.setY(mouseY);
    
    println("Ball is at " + ball.getX() + " " + ball.getY());
    ); // displays 15
    
  • I didn't understand very well your question. However, you can create static variables in order to share them with other classes, but this will turn those variables global to very object of that class.

  • In Processing by default, every class we make is nested to the sketch top-class itself. And every1 shares everything to each other! 3:-O
    Thus somehow, everything is "global"! >:)

Sign In or Register to comment.