How to pass Object from java class to another java class

前端 未结 6 464
抹茶落季
抹茶落季 2020-12-15 14:34

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

ABC ab = new ABC();

I want to access this instant ab in another class

6条回答
  •  被撕碎了的回忆
    2020-12-15 15:00

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

    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
       } 
    }
    

提交回复
热议问题