I understand an interface is a contract and if a class implements that interface, it must define those abstract methods from the interface. What I don't understand is, how is data passed between two classes that use an interface?
So for example: In Android, a Fragment has an interface, say OnFragmentInteractionListener. At someplace in the code it calls,
onFragmentInteractionListener.displaySomeMessage(message);
The Activity will implement:
void displaySomeMessage(String message) {
System.out.println(message);
}
How is "message" actually passed to the Activity? How does it retrieve this specific piece of data? I use interfaces all the time and know how to use them. But I just don't quite understand what the "contract" is actually doing behind the scenes, so that everyone uses the same data.
onFragmentInteractionListener
to a specific implementation (otherwise you'd get a resolution exception). From there it works like any other parameter reference. baeldung.com/java-stack-heaponFragmentInteractionListener
is an object (an instance). It's type is theOnFragmentInteractionListener
interface, but the actual underlying variable is the instance of the activity. You are literally just callingactivity.displaySomeMessage(message)
, except that the variable has a different name, and a different type. This is possible because the activity implements that interface, and therefore is also of that type, by virtue of type inheritance. Somewhere in the activity, you passed it to the fragment usingfragment.setOnFragmentInteractionListener(this)
.