如何将Object从java类传递到另一个java类

问题描述:

我在java中创建了一个类的实例,如下所示:

I created an instance of a class in java as following:

ABC ab = new ABC();

我想在另一个班级 XYZ $ c中访问此瞬间 ab $ C>。如何在XYZ类中使用此对象?

I want to access this instant ab in another class XYZ. How to make this Object available in class XYZ?

如果没有关于您的问题的更多具体信息,很难回答您的问题,但这肯定有用:

It is difficult to answer your question without more specific information about your problem, but this would certainly work:

如果要在其他类中使用它,可以使用setter初始化其他类中的实例变量:

You can use a setter to initialize an instance variable in your other class if you want to use it everywhere in that class:

class someClass {
   void someMethod() {
      ABC ab = new ABC();
      XYZ xyz = new XYZ();
      xyz.setABC(ab);
   }
}

class XYZ {
   ABC ab;
   //...
   void setABC(ABC ab) {
     this.ab = ab;
   }
   //...
   void doSomething() {
      // do something with instance variable ab
   } 
}