Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Use Interfaces. B's relationship with A is only via an Interface that B defines and A implements.</p> <p>So from B's perspective, it doesn't even import A, or have access to the definition of A at compilation time. </p> <p>Edited in response to question.</p> <p>I beleive you have a class C</p> <p>pre-existing, unchangable by you, code in some package x.y;</p> <pre><code>Class CEvent { // some event definition }; Class C { public void callWhenitHappens(CEvent theEvent) { // do something } } </code></pre> <p>--- code you write ---</p> <pre><code>package p.q; public Class A implements BEventInterface { public void bEventHappened( BEvent theBEvent ){ // make a C event myC.callWhenitHappens(theCEvent); } } </code></pre> <p>And your concern is that <strong>anybody</strong>, even including C could call that bEventHappened() method.</p> <p>My feeling is that you're concerned by an unlikely problem. Why would someone go to the trouble of creating an A object and doing that? However there are some possibilities:</p> <p>1). If A and B are in the same package, do not make A and it's method public. Only B needs to see them, so at package scope this will just work.</p> <p>2). Anonymous inner class. Note here that A ia class with a no public methods, so C can't use it and yet B has public methods on the anonymous inner class it can use. </p> <pre><code>package p.q; import p.q.B.BEvent; import x.y.z.C.CEvent; import x.y.z.C; public class A { // anonymous class implementing required interface private BListener myFacade = new BListener(){ @Override public void listen(BEvent event) { bEventHappened(event); } }; private B myB; private C myC; A() { myC = new C(); myB = new B(); myB.registerListener(myFacade); } private void bEventHappened( BEvent theBEvent ){ myC.callWhenitHappens(myC.new CEvent() ); } } </code></pre> <p>With classes B and C looking like:</p> <pre><code>package p.q; public class B { public class BEvent { public String what; } private BListener myListener; private void fireEvent(){ myListener.listen(new BEvent()); } public void registerListener(BListener listener){ myListener = listener; } } </code></pre> <p>and</p> <pre><code>package x.y.z; public class C { public class CEvent { public String what; } public void callWhenitHappens(CEvent event){ //e3c } </code></pre> <p>}</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload