How to Pass the Same Object Across Multiple Classes Java

How to pass an object between multiple classes? Java

That's already exactly how objects work in Java. Your code already does what you want it to.

When you pass theBar to the FooClass constructor, that's passing the value of theBar, which is a reference to a BarClass object. (theBar itself is passed by value - if you wrote foo = new FooClass(); in the BarClass constructor, that wouldn't change which object theBar referred to. Java is strictly pass-by-value, it's just that the values are often references.)

When you change the value within that object using theBar.foo.a, then looking at the value of a again using theFoo.a will see the updated value.

Basically, Java doesn't copy objects unless you really ask it to.

How can i use same object in different classes in Java

So create the object once, and pass it into the constructors of A and B:

C c = new C();
A a = new A(c);
B b = new B(c);

...

public class A
{
private final C c;

public A(C c)
{
this.c = c;
}
}

Note that this is very common in Java as a form of dependency injection such that objects are told about their collaborators rather than constructing them themselves.

Java: Passing 2 objects from 2 different classes and accessing all of their variables

below is a brief version of your code,but this should get going and you can do this with two different classes as well.

public class Player {
private int speed;

public Player(int speed){
this.speed=speed;
}

public int getSpeed() {
return speed;
}

public void setSpeed(int speed) {
this.speed = speed;
}
}




public class Battle {

Player player;

static void battle(Player obj1, Player obj2){
if (obj1.getSpeed() > obj2.getSpeed()){
System.out.println("Faster");
}
else{
System.out.println("Slower");
}
}


public static void main(String[] args) {
// TODO Auto-generated method stub
Player player1 =new Player(5);

Player player2 = new Player(3);

battle(player1,player2);


}

}

Objects of multiple class in java

I'm not really sure why you would want to do that, but assuming you're just wondering about the possibility to implement such a thing - yes, it can be done.

You can create an instance of a class inside that same class, like so:

public class A {
public static A instance = new A();

public void display() {
System.out.println("inside class A");
}
}

Pay attention to the static modifier in the above code; it allows you now to access instance from another place (class, method, main) like so:

A.instance.display();

If you want to know whether you can declare a variable inside a method, and not a class, and make it accessible from another method, then the answer is - no, you cannot.



Related Topics



Leave a reply



Submit