I have created an instance of an object in one of my classes for a Java program. How can I pass the same instance of that object to another class?
Would I need to do something like creating some type of a getter method in the original class to pass the object through to the other class?
You can pass the object via the constructor of the other class.
Simple Example:
Class A{
}
Class B{
A a;
public B(A obj){
this.a=obj
}
}
Let's assume you want to pass an object of class A
to class B
. Now you have created the object like this:
A object = new A ();
And now in your B
class, you can write a method to accept a A
object. It should be public
and you can make it static
if you like.
If you want to pass object
to B
, you must want to do something with it, right? So you should name your method accordingly. You probably want to assign a field of type A
(Let's call this fieldA
) in B
. (or maybe that isn't what you want, but I'll use this for the example)
Let's look at the method:
public void setFieldA (A a) { fieldA = a; }
You can call this method as follows:
anObjectOfClassB.setFieldA (object);
Of course you don't need anObjectOfClassB
if it is static.
To "pass" it you need a method or a constructor in the other class that can accept it:
public class Other {
// either
public Other(MyClass obj) {
// do something with obj
}
// or
public void method(MyClass obj) {
// do something with obj
}
}
Then call the constructor/method:
MyClass x = new MyClass();
Other other = new Other();
other.method(x);
There are many ways to pass the reference for one object to another object. The simplest and most common ways are:
setFoo(Foo foo)
to set the "foo" attribute, or addFoo(Foo foo)
. Then there are a variety of more complicated patterns where objects are passed using publish/subscribe, call-backs, futures, and so on.
Finally there are some tricks that can be used to "smuggle" objects across abstraction boundaries ... which are generally a bad idea.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.