Subsections
Interfaces are a way to declare a type consisting only of abstract methods and related constants, classes, and interfaces. An interface in Java is an expression of pure design, whereas a class is a mix of design and implementation.
Upon completion of this section, students will:
- Describe an interface.
- Define the differences between single and multiple inheritance.
- Show how to implement an interface.
- Describe the differences between interfaces and abstract classes.
- Java has single inheritance of implementation - you can extend only one class.
- Java has multiple interface inheritance.
- All methods in an interface are implicitly abstract.
- Each class that implements the interface must implement all its methods.
- Methods in an interface are always public.
- Fields in an interface are always static and final.
- Nested classes and interfaces let you associate types that are strongly related to an interface inside that interface.
- Any class or interface inside an interface is public.
- Any classes nested inside an interface are also static.
- Any interface nested inside a class can be public, protected, package-accessible, or private.
- A new class can extend exactly one superclass.
- The new class inherits the superclass's (a) contract and (b) implementation.
- Some languages allow multiple inheritance - two or more superclasses.
- Problem of multiple inheritance arises from multiple inheritance of implementation. (Usually related to a class that maintains state information.)
- A class or interface can be a subtype of more than one interface.
- What happens when a method of the same name appears in more than one interface?
- Most interfaces may have several useful implementations.
- Enumeration is an interface.
- Use an implementing class just by extending it.
- Can also use a technique called forwarding - create an object of an implementing class and forward all the methods of the interface to that object.
- Do not declare any methods - mark a class as having some general property.
- Define no language-level behavior.
- All of the contract is in the documentation.
- Interfaces provide a form of multiple inheritance. A class can extend only one other class.
- Interfaces are limited to public methods and constants with no implementation. Abstract classes can have a partial implementation, protected parts, static methods, etc.
- These two differences usually direct the choice.
- If multiple inheritance is important or even useful interfaces are used.
- Abstract class lets you define some or all of the implementation.
- Any major class you expect to be extended should be an implementation of an interface.
|
|