0

I have file Sender.java and another Receiver.java. In my main class which is in file Main.java, I created an object for both. I want to access a variable that is in my Sender class into Receiver class. what is the simplest way to do it. I extended the Sender class onto my receiver class and it serves the purpose. Albeit, is there any other way to do it?

Main.java

class Main{
    public static void main(String args[]){

        Sender sender=new Sender();
        Receiver receiver=new Receiver();
        sender.show();
        receiver.show();


    }
}

Sender.java

class Sender{

    static int val=0;
    public void show(){

        System.out.println("Sender value="+val);
        val++;  
    }

}

Receiver.java

class Receiver{
    public void show(){
        System.out.println("Receiver value="+val);  
    }
}
YowE3K
  • 23,852
  • 7
  • 26
  • 40
Suraj Jeswara
  • 446
  • 2
  • 10
  • 23

2 Answers2

1

As mentioned already, getters and setters should be your answer. Why use getters and setters/accessors? explains the purpose of them.

Patrick M
  • 113
  • 1
  • 7
1

The simplest way is to make the variable public. although this is not necessary if the classes are in the same package.
The more important issue here is - you need to pass an instance of Sender to Recevier.
You also need to understand whether you want the variable static or not. My guess - not static (so a different copy of the variable with every instance of Sender)

class Sender{

    public int val=0;
    public void show(){

        System.out.println("Sender value="+val);
        val++;  
    }

}

class Receiver{
    public void show(Sender s){
        System.out.println("Receiver value="+s.val);  
    }
}

class Main{
    public static void main(String args[]){

        Sender sender=new Sender();
        Receiver receiver=new Receiver();
        sender.show(sender);
        receiver.show();


    }
}
Sharon Ben Asher
  • 13,849
  • 5
  • 33
  • 47