Last week my lecturer was teaching us about interfaces in Java.
However, I failed to understand her explanation that well.
Does anyone have a good description, or explanation of Java interfaces, and reasons to make use of them?
Last week my lecturer was teaching us about interfaces in Java. However, I failed to understand her explanation that well. Does anyone have a good description, or explanation of Java interfaces, and reasons to make use of them?
| |||||||
feedback
|
Interfaces are a concept that is very similar to, but essentially orthogonal to inheritance. The basic difference is that java classes can only have one parent class; there is only one thing a derived class can inherit from. The problem with this is that sometimes you would want to use things that are too unrelated to each other to inherit from the same parent, but you want to use them for the same things. Suppose you're modeling building materials; You have Thing is, What this suggests is that it should inherit from none of them; It should just be a specialization of Interfaces do exactly that; a java interface doesn't specify how any implementation actually does a thing, only that it can do that thing. | |||
feedback
|
As for the why people use it, there are two basic reasons:
| |||
feedback
|
Interfaces in Java define a contract specification. Meaning, an arbitrary class X might depend on a feature expected to be implemented by interface Y, but doesn't necessarily care about how that feature is implemented, as long as it produces the result or process that X depends on. So one could create another class Z to implement interface Y and pass it on to X. This generates flexibility, as one could always choose to supply class X with a different, possibly more efficient, or specialized version of the feature implemented by interface Y. Depiction:
| ||||
feedback
|