Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two independent classes that communicate using an Interface [closed]

Tags:

java

interface

Is it possible to have two independent class communicate by implementing an interface, and if so, how?

like image 524
Med Avatar asked Dec 02 '22 23:12

Med


1 Answers

I think that using interfaces is a little extreme here but i'm assuming this is a simplification of a larger problem

public interface SomeInterface {

    public void giveString(String string);

    public String getString();

}


public class Class1 implements SomeInterface{

    String string;

    public Class1(String string) {
        this.string = string;
    }

    //some code

    @Override
    public void giveString(String string) {
        //do whatever with the string
        this.string=string;

    }

    @Override
    public String getString() {
        return string;
    }



}


public class Class2 implements SomeInterface{

    String string;

    public Class2(String string) {
        this.string = string;
    }

    //some code

    @Override
    public void giveString(String string) {
        //do whatever with the string
        this.string=string;

    }

    @Override
    public String getString() {
        return string;
    }

}


public class Test{

    public static void main(String args[]){
        //All of this code is inside a for loop
        Class1 cl1=new Class1("TestString1");
        Class2 cl2=new Class2("TestString2");

        //note we can just communicate now, no interface
        cl1.giveString(cl2.string);


        //but we can also communicate using the interface
        giveStringViaInterface(cl2,cl1);
    }

    //any class that extended SomeInterface could use this method
    public static void giveStringViaInterface(SomeInterface from, SomeInterface to){
        to.giveString(from.getString());
    }



}
like image 172
Richard Tingle Avatar answered May 08 '23 05:05

Richard Tingle