A brief overview of Interface

interface as the name stands for , give you ability to quickly setup a way to let your objects talk to each other,It's a one way of internal communication (not external IPC / interprocess communication). A callback is a good example of that.I'm not gonna to explore all details about interfaces but just to show you by example how to use the basic function of its existence!:

Intefrace is a class with just signature of your methodes without implementation , implementation will be delegated to any class which like to use it in order to make such a communication possible.interface setup communication between objects in a proper way by abstraction.All class's implementing an interface called Concrete Class.

Suppose you have Two Class A and B ,B calculate a complex mathmatical routine then at the end when calculation is over,  send the result back to Class A.

There are many solution to resolve this issue , you may want to use Handlers, messaging, Intent or any other...but remember even a good solution depends to exact scenario in your algorithm, non of them can perform this task as good as interface!


Solution 1: using an anonymous class :

interface IB2A {

void onFinishCalculation(double result);

}

Class A {

....

B b = new B();

....

//calling math function in B with a simple inline anonymous class as delegate

 b.mathFunctionX(100.0, new IA2B() {

            @Override

            public onFinishCalculation(double result) {

                //do something with result

            }

        });


}


Class B{

    .....

    void mathFunctionX(double input, IB2A a2b){

    double result = 0

    ......

    //perform a mathmatical operation

    result = xxxxx;

    a2b.onFinishCalculation(result)

    }


}





Solution 2: by implementing interface in A (making Class A as Concrete class)

class A : implements IB2A{

    B b = new B();

    ....

    //calling math function in B with a simple inline anonymous class as delegate

     b.mathFunctionX(100.0, this)


    @Override

    public onFinishCalculation(double result){

    //do something with result

    }


}


Class B{

.....

    void mathFunctionX(double input, IB2A a2b){

    double result = 0

    //perform a mathmatical operation

    result = xxxxx;

    a2b.onFinishCalculation(result)

    }


}




Interfaces are wastely used today as a proper way to implement communication between different object and module on device, Interface is specially good when your project follow a design pattern model.






 © Xosrov 2016