What is an Interface?

What is an Interface?

I have no experience with object-oriented languages, havingonly learned BASIC when I was a child. Most people say Java is easy,but in my case it’s not. I don’t understand the keyword ‘implements’, Idon’t understand ‘interface’. Is there anydifference between a class and aninterface? Without an interface, are there any functions that a Java programmercan’t use?

I think most people would agree that Java isn’t all that easy, especiallyif you come from a BASIC background and have not yet delved deeply into object-oriented programming.

Let me review a few concepts first, before getting to your question.

The basic concept of object-oriented programming is, naturally enough, theobject. An object carries with it some data that describe its currentstate. And each objects has certain functions that it can carry out. Forexample, an AudioFile object may store a name of a wav file and carry outthe function “play”.

Objects of the same type are grouped into classes. A class specifies whatfunctions its objects can carry out, and what data they store. For example,

     class AudioFile     {  // functions        public void play();        // data        private String filename;     }     

By the way, the official Java speak for “function” is “method,”; for”data,” it’s “instance variable.” But I’ll stick with the more familiar termsfor now.

The idea is that you should not access the object data directly. That iswhy they are declared private. You read and change the object state throughthe public functions.

It often happens that one class is a refinement or specialization ofanother. For example, suppose you design a class ElevatorMusic (for thoseJava-powered elevators) that keeps playing the audio over and over. Toindicate that this class is a special case of an audio file, you use theextends keyword.

     class ElevatorMusic extends AudioFile     {  public void play();     }     

This says: an ElevatorMusic object is just like an AudioFile object, exceptthe details of the play function are different. In particular, you don’thave to figure out how the audio data are stored–the AudioFile class takescare of that. We say that the ElevatorMusic inherits thatcapability.

This concept of inheritance is powerful because it lets you reuse existingclasses. In fact, it is so useful that you may want to inherit from twoclasses at the same time:

     class ElevatorEntertainment extends AudioFile, NervousText          // not legal Java     { . . .     }     

Unfortunately, that is not possible in Java. Some languages, such as C++,support this multiple inheritance, but they pay a high price. Thelayout of the object data gets very complex when you have more than oneparent class. The designers of Java wanted to avoid the complex and murkycorners of C++, so they decided not to support multiple inheritance.

But there are times when you really need to inherit from two classes. Everyapplet must extend the class Applet. Every class that wants to run code ina thread must extend the class Thread. But you can’t code:

     class ElevatorApplet extends Applet, Thread          // not legal Java     {  public void init() { /* applet initialization code */ }        public void run() { /* thread code */ }        . . .     }     

What to do? This is where interfaces come in.

An interface is a class without data, only with functions.

     interface Runnable     {  public void run();     }     

All the complications of data layout of multiple parents go away when youdon’t have any data, so Java is happy to let you inherit as many interfacesas you like:

     class ElevatorApplet extends Applet          implements Runnable, ImageObserver     {  public void init() { /* applet initialization code */ }        public void run() { /* thread code */ }        . . .     }     

In practice, when do you need to worry about interfaces? If you mostly usethe existing Java library, you don’t usually need to design your owninterfaces. But if you write code that other programmers reuse, you mayneed to supply a few interfaces yourself.

The standard Java library defines 18 interfaces:

        Runnable        Cloneable        Enumeration        Observer        FilenameFilter        DataInput        DataOutput        SocketImplFactory        ContentHandlerFactory        URLStreamHandlerFactory        LayoutManager        MenuContainer        ImageConsumer        ImageObserver        ImageProducer        AppletContext        AudioClip        AppletStub                

Most of them are extremely technical and are only used to implement other Javalibrary features. The ones you are likely to implement yourself areRunnable (for multithreading) and maybe ImageObserver (to monitor theloading progress of an image).

Occasionally you will handle objects of type Enumeration, AudioClip orDataInput. But as a user you don’t care that these are really interfaces,not classes.

So, here is the answer to your question in a nutshell:

An interface is a class without data You use “implements” to inherit an interface, “extends” to inherit a class.

In practice, you don’t need to worry too much about interfaces. You implement Runnable when you need multithreading, for example for animation. Otherwise, you can leave interfaces to the library builders.


Share the Post: