Java is an Object Oriented Programming Language(OOP). OOPs basic principals include Objects, Class, Data Abstraction, Data Encapsulation, Inheritance, Polymorphism etc. Data Abstraction is the ability to take advantage of the features without knowing about unimportant background details. Interface helps achieve this in any compiler based oop languages. Interface consists of abstract methods. The abstract class alone may achieve partial abstraction but when implemented with interface complete abstraction can be achieved. Now let's find out how it works.

Let’s consider the class FetchData that obtains data from the internet running on background thread where data is also processed. Now on the main ui thread in class MyMainThread, the ui would get updated when the background thread completes execution.

class FetchData { MyInterface myInterface; FetchData(MyInterface myInterface){ this.myInterface = myInterface; } …… // background task runs returns result in onPostExecute onPostExecute(JSONObject jsonData){ myInterface.resultsReceived(jsonData); } } public interface MyInterface{ void resultsReceived(jsonData); // abstract method } class MyMainThread implements MyInterface{ void getData(){ FetchData fetchData =new FetchData(this) } @Override void resultsReceived(JSONObject jsonData){ // update ui } }

Now the interface MyInterface implemented by MyMainThread consists of an abstract method resultsReceived that works as a bridge to separate business logic and ui main thread. Interface can also act as a listener for when a process is completed or interrupted.

Loading full article...