Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 9 Interfaces and Polymorphism. 9.1 Reusing Code An interface is a collection of related methods whose headers are provided without implementation.

Similar presentations


Presentation on theme: "Chapter 9 Interfaces and Polymorphism. 9.1 Reusing Code An interface is a collection of related methods whose headers are provided without implementation."— Presentation transcript:

1 Chapter 9 Interfaces and Polymorphism

2 9.1 Reusing Code An interface is a collection of related methods whose headers are provided without implementation code. (abstraction) Methods are automatically public

3 Interfaces Provide a framework for behavior Classes which use the interface may have vastly different objects, but what they have in common is expressed in the interface

4 Example Interface FlyingObject Methods isFlying() fly() Example Classes: Bird, Airplane, Missile, Butterfly, Witch Non-Examples: Turtle

5 Example Interface Computable Methods add(), subtract(), multiply() Example Classes: Fraction, Matrix, LongInteger, ComplexNumber Non-Examples: TelevisionSet

6 Defining an Interface public interface InterfaceName { method headers }

7 Defining an Interface Example public interface FlyingObject { void fly(); boolean isFlying(); }

8 Implementing an Interface public class className implements InterfaceName, InterfaceName { methods fields }

9 Warning: Must define all methods of an interface if you want to use it.

10 UML FlyingObject > Witch

11 Implementing an Interface Example public class Witch implements FlyingObject { methods fields }

12 9.2 Interface Types and Class Types It is legal to have a variable of an interface: FlyingObject x; However, x is NOT type FlyingObject Why not?

13 Witch wicked = new Witch(); FlyingObject y = wicked; //OK TelvisionSet tv = new TelevisionSet FlyingObject y = tv; //NOT OK Type of interface variable must be of a class which implements the interface

14 Casting Interfaces What if I needed to use another method from the Witch class that is NOT in the interface? Use a cast (Witch) y If you cast incorrectly, program will cause an error

15 9.3 Polymorphism Polymorphic Methods: Methods which are overridden in more than one class Polymorphism: The ides that the type of object determines which form of the method is called

16 Overloaded vs. Polymorphic


Download ppt "Chapter 9 Interfaces and Polymorphism. 9.1 Reusing Code An interface is a collection of related methods whose headers are provided without implementation."

Similar presentations


Ads by Google