Akira
Akira

Reputation: 11

How to pass data from a class to another class if they are in the same package

I have been doing this program and I had to pass a data from a class to another class, but they are in the same package. How am I supposed to do it?

Upvotes: 0

Views: 50

Answers (3)

Adarsha
Adarsha

Reputation: 21

You can create two public classes A and B. Then, instantiate (create an instance) of A in B or vice versa. Now, you have an object of the other class. Using public setter and getter methods, you can easily set and get data of the other class.

Hope this helps!

Upvotes: 0

Manoj Suthar
Manoj Suthar

Reputation: 1455

Instantiate the first class in second class's constructor and use it like this:

class DataSource{
   int x=2;
   //setter getter
}

class DataConsumer{
   DataConsumer(){
      DataSource d = new DataSource();
   }
   //use it then
   d.getX();
}

Upvotes: 1

you need to define an object ob the classB and use setters and getters

example:

    class A{

    private int counter;

    public void setCounter(int c){
       this.counter = c;
    }
public int getCounter(){
   return c;
}

Class B{
private A myObject;
//constructor
B(){
    A a = new A(); // initialize A;
}
public void setValueInA(int val){
     a.setCounter(val); // here is the value "passed" to the class A

}

Upvotes: 0

Related Questions