Home > Software design >  Java passing data between multiple classes
Java passing data between multiple classes

Time:12-13

Is it possible to pass data between multiple classes?

class Original{
   private int x;

   public void setX(int x){
      this.x = x;
   }
}
//
class Setter{
   Original original = new Original();

   original.setX(5);
}
//
class Consumer{
   //use the value "5" here which came from Original->Setter
}

What I am trying to achieve is "one class sets the value of some class and other class accesses it" -(java beginner)

CodePudding user response:

welcome to stackoverlflow!

You also need a getX() method in the Original class, and you need constructors to reach your end result.

Then it would be like so:

public class Original {
    private int x;

    public void setX(int x) {
        this.x = x;
    }

    public int getX() {
        return x;
    }
}

public class Setter {
    public Original mOriginal = new Original();

    public Setter() {
        mOriginal.setX(5);
    }
}

public class Consumer {
    private Setter mSetter;

    public Consumer(Setter setter) {
        mSetter = setter;
    }

    public void doSomethingWithOriginal() {
        System.out.println(mSetter.mOriginal.getX());
    }
}

CodePudding user response:

class Original{
    private int x;
    public void setX(int x){
        this.x = x;
    }
    public int getX(){
        return x;
   }
}
class Setter {
    private Original original;
    Setter (Original o) {
        original = o;
    }
    public void set(int x){
        original.setX(x);
    }
}
class Getter {
    private Original original;
    Getter (Original o) {
        original = o;
    }
    public int get(){
        return original.getX();
    }
}
public class MyProgram {
    public static void main (String args[]) {
        Original original = new Original();
        Setter setter = new Setter (original);
        Getter getter = new Getter (original);
        setter.set(5);
        getter.get();
    }
}
  •  Tags:  
  • java
  • Related