Java 使用接口进行通信的两个独立类

Java 使用接口进行通信的两个独立类,java,interface,Java,Interface,有没有可能通过实现一个接口让两个独立的类进行通信,如果有,如何进行通信?我认为在这里使用接口有点极端,但我假设这是一个更大问题的简化 public interface SomeInterface { public void giveString(String string); public String getString(); } 接口I1{void foo();}接口I2{void bar(I1 I1);}?你的问题不是很清楚。也许你可以告诉我们你想解决的问题?

有没有可能通过实现一个接口让两个独立的类进行通信,如果有,如何进行通信?

我认为在这里使用接口有点极端,但我假设这是一个更大问题的简化

public interface SomeInterface {

    public void giveString(String string);

    public String getString();

}




接口I1{void foo();}接口I2{void bar(I1 I1);}
?你的问题不是很清楚。也许你可以告诉我们你想解决的问题?是的,这是可能的。这两个类都实现了接口。接口指定了便于通信的方法。它们试图通信什么?我想使用java接口将字符串从一个类传递到另一个类,并且这些类是独立的。我认为这个示例非常有用,非常感谢您的回答,
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());
    }



}