Design Tools |
To demonstrate this concept, let's look at an interface commonly used in Java: java.util.Collection
of objects that are instantiated from some class that implements either the Collection interface or an extension of that interface.
Take, for example, the following method:
public void printCollection(Collection<String> c) {
java.util.Iterator iterator<String> = c.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
Let's assume that the above method is part of a class Printer which has a default constructor. Let's further assume that objects a, b, and c exist of class java.util.ArrayList
Printer p = new Printer();
p.printCollection(a);
p.printCollection(b);
p.printCollection(c);
How do I know the above code will execute successfully? Because java.util.ArrayList
The ability for objects a, b and c to change their form so that they can be used as objects of the type Collection is called polymorphism, which is a concept fundamental to object oriented programming.
How Is This Useful?
Interfaces allow us to build flexible software because we don't actually have to know the implementation of a class to accept a type as an argument. And because specifying an argument creates a dependency, we can create dependencies on contracts (interfaces) instead of implementations (classes). This allows any class that adheres to the contract defined by the interface to b interchanged with any other class adhering to that same interface. And that is how loosely coupled software and more maintainable software begins.
No comments:
Post a Comment