Interfaces
Last modified Sunday, 07-Jul-2024 16:06:39 UTC.
- Interfaces
- An interface is a collection of abstract methods and
public static final values.
- A class that implements a specified interface inherits
the final values, and is known to have implementations
of the methods.
The interface forms a contract between its abstract methods and
classes that implement the interface.
- The
String class implements the
Comparable interface, which allows use of the
Array.sort method to sort an array of Strings.
- Implementing an interface requires providing implementations of
the interface's methods.
- Uses for interfaces
- Designing what a class should do
- Extending the power of polymorphism, by using variables of
the interface type to reference objects that implement the
interface.
Then the interface methods can be called using such variables.
- A class can implement multiple interfaces, but can extend only
one superclass.
- Example:
ProvidesValue.java,
Apple.java,
Orange.java,
UseFruit.java
Exercises
- Explain the difference between an abstract class and an interface.
Exam Style Questions