Chapter 09

11
Interfaces Chapter 9

description

 

Transcript of Chapter 09

Page 1: Chapter 09

Interfaces

Chapter 9

Page 2: Chapter 09

9

Creating InterfacesAn interface is a contract.

Every class that implements the interface must provide the interface’s defined methods.

Each class implements the methods however it sees fit.

A class can implement multiple interfaces.

Page 3: Chapter 09

9

Declaring the InterfaceSimilar to a class declaration but uses the interface keyword

The extends keyword can be used to extend interfaces.

Page 4: Chapter 09

9

Interface RestrictionsInterfaces:

Cannot have member fields

Can define constants

Cannot have methods with implementation; all methods in an interface are implicitly abstract

Cannot be instantiated

Cannot define constructors

Page 5: Chapter 09

9Implementing Multiple Interfaces: The Debuggable InterfaceDebugging is an important step in the

programming cycle.

One way to debug a program is to display information about objects and variables to ensure their validity.

Page 6: Chapter 09

9

Debugging an InterfaceIn the ball program, seeing information about each of the objects as the program runs is helpful.Ball and Wall classes do not derive from the same base class (Java does not support multiple inheritance).

Ball and Wall can implement common interfaces.

Page 7: Chapter 09

9

The Debuggable InterfaceThe Debuggable interface defines two public methods:displayStatus(String identifier);

displayError(String error);

The interface does not define how to implement these methods.

Implementation details are left to the classes.

Page 8: Chapter 09

9

Interfaces vs. Abstract ClassesUse an abstract base class if:

You are trying to create an is a relationship:

A tree is a plant

A fly is an insect

You do not want to instantiate the base class.

Page 9: Chapter 09

9

Interfaces vs. Abstract ClassesUse an interface if:

You are not trying to create an is a relationship.

You are stating that your class has these capabilities.

A Ball and a Wall have the capability of being colorable and debuggable.

You need a way to handle multiple inheritance.

Page 10: Chapter 09

9

Extending InterfacesInterfaces can be extended just like classes.

Allows the programmer to provide new functionality without rewriting existing code

Use the keyword extends: interface DebugLogging extends Debuggable

Page 11: Chapter 09

9

Polymorphic InterfacesInterfaces can be treated polymorphically, as a type.

A method that accepts an object which implements the Debuggable interface will also accept any object which implements any interface derived from the Debuggable interface.