Software Interfaces
A software interface is a contract that defines how one piece of code can interact with another.
Apprentice · Java · OOP · Updated
Not all interfaces are designed for users. In User Interfaces, we saw how a user can interact with some software, but software also needs to have the ability to interact with other software.
Even within the same application, a class needs the ability to interact with other classes. A visual "user" interface would not be appropriate. Instead, we create software interfaces that define how one piece of code can interact with another.
In other words, you can think of an interface as a contract that defines how software can interact (or communicate with) another piece of software.
Do it: count the letters on a sign
A sign shop prints name signs and charges by the letter. Its customers send the names in different collections: sometimes a List<String>, sometimes a Set<String>. One method should count the letters in either.
Java's own collections keep a contract for this: Collection<String> is an interface, and both List and Set keep it. A method whose parameter is a Collection<String> only asks for what every collection can do, such as looping through it, so it takes a list or a set.
The method gets one value:
names: the names to print, each one a single word with no spaces.
For example:
List<String> names = List.of("Ada", "Grace");
| Name | Letters |
|---|---|
| Ada | 3 |
| Grace | 5 |
| The sign | 3 + 5 = 8 |
So letterCount(names) returns 8.
Your job: write the method letterCount(Collection<String> names) so it returns an int: the letters in all the names, added up.
- The parameter's type is
Collection<String>, so the method takes a list or a set. The starter asks for aList<String>, so it doesn't compile yet: a test sends a set. Change the type. - Each name's letters are its
length(). - No names make
0.
Practiced live on the lesson page: write the Java right there and check it.