您的位置:寻梦网首页编程乐园Java天地Core JavaJava Lecture Notes

Introduction

Content

Apply

Reflect

Extend

previous.gif
 (3087 bytes)

next.gif
 (2959 bytes)


Content Index

Content Page # 10

Interfaces — templates for classes

An interface is a class that declares methods, but does not define them. This means that the class contains no real program instructions. It exists only to take part in a subclass-base class relationship

The concept of an interface can initially be conceptually difficult. You may have to go over the next few sections several times to be sure you understand.

In the multiple inheritance example, we wanted MyButton to be a subclass of both Component and KeyboardListene r . This was not allowed, because Java does not support multiple inheritance. However, if we define either Component or KeyboardListener as an interface (not a true class) then we can define MyButton to inherit from both.

But the use of interfaces is only an organisational feature; an interface cannot contain any program instructions. It is not really obvious which of the two entities ( KeyboardListener or Component ) should be an interface and which a class. In reality, Component is very complex, and is defined as a class, while KeyboardListener (which only has a few methods) is defined as an interface.

But if KeyboardListener is defined as having methods, and it cannot implement them itself (because it is an interface, not a class), where are these methods implemented? In this case they must be implemented in MyButton (which is a `subclass' of KeyboardListener ). This will be illustrated below.

Back to top

basicline.gif (169 bytes)

RITSEC - Global Campus
Copyright ?1999 RITSEC- Middlesex University. All rights reserved.
webmaster@globalcampus.com.eg