Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is it possible to communicate between two classes in Java using an interface?

Hi ive been reading on some similar topics here but none of them answer my question. Some say you cant even do this which is not a good thing since I cant finnish my course in that case.

Heres som simple code. Think of each block as a separate class.


public interface Interface {

    void printMessage(String meddelande);

}

public class Model implements Interface {

    String message = "hej!";

    public static void main(String[] args) {

        Model model1 = new Model();

        View view1 = new View();

         model1.printMessage(model1.message); //Ska jag anropa funktionen såhär ens?

    }

    public void printMessage(String str) {

    }

}

public class View implements Interface {

    printMessage(String str) {

    }

}

So, how is it now possible to tel the view to print this string from the model class without the classes knowing about each other? Its not allowed to send a reference of the model-objekt to the view-object. ; (

like image 769
Peter Kanerva Avatar asked Jul 15 '26 06:07

Peter Kanerva


1 Answers

Define an Interface:

public interface MyInterface {

    void printMessage(String str);

}

Define a class that can trigger the notification:

public class ClassNotifier {

    MyInterface mInterface;

    public ClassNotifier(MyInterface mInterface) {
        this.mInterface = mInterface;
    }

    public void triggerTheMsg(String msg) {
        if (mInterface != null) {
            mInterface.printMessage(msg);
        }
    }
}

Define a class that will be informed:

public class InformedClass implements MyInterface {

    public static void main(String[] args) throws Exception {
         InformedClass c = new InformedClass();
         ClassNotifier cn = new ClassNotifier(c);
    }

    @Override
    public void printMessage(String newMsg) {
        System.out.println("A new msg is here: " + newMsg);
    }
}

How does it works?:

this is named a callback parttern, the class ClassNotifier has a reference to the interface MyInterface, which is impl. by Informed class to, so every time the ClassNotifier calls the method printMessage, the method printMessage in the class Informed will be triggered too.

like image 187
ΦXocę 웃 Пepeúpa ツ Avatar answered Jul 17 '26 18:07

ΦXocę 웃 Пepeúpa ツ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!