如何将Object从java类传递到另一个java类 [英] How to pass Object from java class to another java class

查看:119
本文介绍了如何将Object从java类传递到另一个java类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

ABC ab = new ABC();

我想在另一个班级 XYZ 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
   } 
}

这篇关于如何将Object从java类传递到另一个java类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆