Chapter 5 Interface CSC 113 Computer programming II

  • Slides: 20
Download presentation
Chapter 5: Interface CSC 113: Computer programming II 1

Chapter 5: Interface CSC 113: Computer programming II 1

Interface • An interface is a reference type, similar to a class, that can

Interface • An interface is a reference type, similar to a class, that can contain only constants and method signatures. • To define an interface use the keyword interface instead of the keyword class. • All method declarations in an interface are implicitly public, so you can omit the public modifier. • A class must implement an interface • A class implements an interface if it provides the method body to all abstract methods defined in the interface • Interfaces cannot be instantiated—they can only be implemented by classes or extended by other interfaces. Extension is discussed later in this lesson. 2

Example public interface A { public void x(); public double y(); } public class

Example public interface A { public void x(); public double y(); } public class B implements A { public void x(){ } public double y(){ } } //Implements the body of y 3

4

4

5

5

6

6

7

7

8

8

9

9

10

10

11

11

12

12

13

13

14

14

15

15

16

16

ad , String ad 17

ad , String ad 17

Same as for (int i=0; i < payable. Objects. length; i++) { Payable current.

Same as for (int i=0; i < payable. Objects. length; i++) { Payable current. Payable = payable. Objects[i]; System. out. printf (-----------------); 18 }

19

19

Derived Interfaces (Example) interface Monster { void menace(); } interface Dangerous. Monster extends Monster

Derived Interfaces (Example) interface Monster { void menace(); } interface Dangerous. Monster extends Monster { void destroy(); } interface Lethal { void kill(); } Interface Vampire extends Dangerous. Monster, Lethal { void drink. Blood(); } class Very. Bad. Vampire implements Vampire { public void menace() { } public void destroy() { } class Dragon. Zilla implements Dangerous. Monster { public void menace() { } public void kill() { } public void destroy() { } } public void drink. Blood() { } } 20