-4

Say there are two classes A , B and class B has a button object and when i click the button class B should inform class A. I should do this by creating an interface between the classes and implementing it. how do i do this ? thanks.

what i have done is this

    interface Listener{
     void clicked();
    }

    class A implements Listener{
     void clicked(){
     // click informed to A
     }
    }

    class B {
     Button b = new Button();
     Listener l = new A()

     // say this method gets called by the button when it is pressed
     void buttonIsClicked(){
      l.clicked();
     }

    }

i have done it like this but my guide says that i am creating a new "A" and so its like i am informing to a new guy that the button is clicked. i don't get how do i inform "A" without creating an object of "A".

pls help

pradeep
  • 11
  • 2

2 Answers2

0

Consider applying Observer pattern to your code. Class B should hold (injected) list of Listeners and shouldn't know anything about concrete listeners implementations. This will allow you to decouple Subject (Class B) from Observers.

Jakub Bibro
  • 1,570
  • 13
  • 17
-3

Do you absolutly have to use interface for this? Another way of communicating between classes is through Local Broadcast Receiver. To checkout how to handle communication using this checkout This post.

Community
  • 1
  • 1
Shashank Udupa
  • 2,173
  • 1
  • 19
  • 26
  • 1
    1) This question is far too broad (or very unclear) and as such can't and shouldn't be answered. 2) OP is asking a general design question. A specific Android mechanism is itself not a good answer. – Seelenvirtuose May 15 '16 at 06:29
  • Especially because nothing in the question says Android. It could easily be a Swing program or something else entirely. – Andreas May 15 '16 at 06:30