Interfaces
Python |
Java |
An interface is not a distinct program
component. However, the set of methods
belonging to a data type can be viewed by running either the dir or the help
functions with that data type as an argument. Examples: print(dir(int)) print(help(list)) dir
returns a list of the names of the typeճ attributes, including
method names. help returns a string consisting of the docstrings of the type and all of its methods. |
An interface consists of a name and a set method headers. It
specifies the set of methods that an implementing class must include. The interfaces of the built-in classes can
be viewed in the JavaDoc. A single class can implement several different
interfaces. An interface guarantees a common, abstract behavior
of all implementing classes. For
example, the java.util.List
interface specifies methods for all classes of lists, including java.util.ArrayList
and java.util.LinkedList. An interface can extend another, more general
interface. For example, the List
interface extends the Collection
interface. This means that all of the methods required by the Collection
interface will also be required for all lists. Interfaces are like the interstitial glue that
holds program components together.
Whenever possible, use interface names for the types of variables,
parameters, and method return types. Uses of interfaces: List<String> aList
= new ArrayList<String>(); aList.add(("Mary"); aList.add("Bill"); Collections.sort(aList); The ArrayList
class implements the List interface. Note the use of List
rather than ArrayList
and LinkedList to type the list1
and list2 variables. The method Collections.sort
expects a Collection of Comparables
as an argument. Because the String
class implements the Comparable
interface and the List interface extends
the Collection interface, the compiler does not complain and all goes well. Finally, note that the LinkedList constructor can accept a Collection as an argument. This allows a new list to be built from the elements contained in another list, regardless of implementation. |