Saturday, July 30, 2016

Interface Aha Moment

So yesterday programming from this Android training document: I totally realized what interfaces were actually used for. Albeit, I am a little embarrassed to say that I hadn't learned this properly earlier. Nevertheless, I am very happy to wrap my head around what an interface is and how it is used.

My understanding is that when you have two classes, one can create an object for the class and then call it's public methods to communicate with that object. Now if that object wants to communicate with the first class object there is a problem doing it the same way. Because if the second class creates a new object and calls public functions of that class, then there are actually two instances of the first class.

The way to navigate this properly is to make an interface in the second class, which is pretty much a method declaration, get a reference (a cast) of the first object, and then in the first class write the method implementation. This way the second class can pass an argument through that interface method to the first class.