您的位置:寻梦网首页编程乐园Java天地Core JavaJava Lecture Notes
Introduction
Content
Apply
Reflect
Extend
previous.gif
 (3087 bytes)
next.gif
 (2959 bytes)

 
 
Content Index
Content Page # 13

What have we gained by using interfaces?

Interfaces do not provide `real' multiple inheritance. They provide an approximation to it for simple classes. They help to organise a complex program.

The use of interfaces seems quite complicated at first, and the student can't be blamed for wondering whether their use gives any real benefits. The importance of interfaces becomes apparent when programs become more complicated. Suppose I define a method in Java like this: 

void doSomething(Object someObject)
{
  someObject.keyPressed();
}
This method does not know what kind of object will be passed into it. It could be anything. For this method to succeed, the class of which someObject is a member must be defined to have a method called keyPressed() . At what point will the Java system check whether this is the case or not? The Java run-time engine could easily check when the program is executing, and call the method if it is, or abort the program if it is not. But it would be nice to be able to write the program in such a way that we found out potential errors very quickly. The way to do this is as follows: void doSomething(KeyboardListener someObject)
{
  someObject.keyPressed();
}
Now any object that implements the KeyboardListener interface can be passed to this method, and anything else will be rejected. So if I write MyButton newButton = new MyButton();
SomeMethod (newButton);
This will be fine, because MyButton implements the interface KeyboardListener . On the other hand, if I (accidentally) try to pass an object of class Component (for example) to this method, e.g., Component newButton = new Component();
SomeMethod (newButton);
it will be rejected immediately by the compiler.

Even though the use of interfaces does not limit the amount of program code the programmer has to write, it does prevent the programmer making trivial errors that cannot be detected by the compiler. It also help to clarify the structure of the program, making it easier to maintain and update.

Back to top

basicline.gif (169 bytes)

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