简体   繁体   中英

Pass current instance of class to a newly created one

So I have a class A which needs to create an instance of class B in some cases. If this happens class B needs to be able to call methods of the instance of class A which created it.

How can I achieve this in the best way possible in Java? Can I pass the current instance of the class to the second one I am creating so I can access the methods of it, or is there a way to actually pass methods?

A good way to do it is by creating an Interface with function that are required to be call by class B, and implement this Interface via class A. Now, when creating an instance of class B inside class A, pass the reference of class A object to class B through constructor. eg

interface IA{
void foo();
}

class B{
    IA aInstance;
    public B(IA temp){
        aInstance = temp;
    }
    //call function of A from anywhere like inside this function
    void function(){
        aInstance.foo();
    }
}
class A implement IA{
    B bInstance;
    public A(){
        bInstance = new B(this);
    }
    void foo(){
       //Implement foo here
    }
}

Hope this will help.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM