Why Java interface?

M

Mary Wenge

This seems to be a beginner's question.

We can feel the advantages of class inheritance from at lease sharing
and reusing the super class's methods. But in an interface, there are
only abstract methods, and we have implement all the methods in the
class that implements this interface, why do we still use interface?
Why don't we define the methods and write their code directly in the
class without implementing any interface or something like that? In
other words, what are the advantages of using interface? I have read
some books, in which the authors just say it's a protocol and so on. I
still can not understand the necessity of using interface. Can anybody
give me a sample to illustrate this? Thanks.

Merry Christmas!
 
S

Steve W. Jackson

:This seems to be a beginner's question.
:
:We can feel the advantages of class inheritance from at lease sharing
:and reusing the super class's methods. But in an interface, there are
:eek:nly abstract methods, and we have implement all the methods in the
:class that implements this interface, why do we still use interface?
:Why don't we define the methods and write their code directly in the
:class without implementing any interface or something like that? In
:eek:ther words, what are the advantages of using interface? I have read
:some books, in which the authors just say it's a protocol and so on. I
:still can not understand the necessity of using interface. Can anybody
:give me a sample to illustrate this? Thanks.
:
:Merry Christmas!

It's not necessity at all, in most cases. If you really want to just
define the methods in the class and not "implement the interface", you
can certainly do that. But one big advantage of using an interface is
the "is a" test.

For example, one very commonly used interface is ActionListener. It
defines only one method, actionPerformed(ActionEvent). If your class
includes "implements ActionListener", then an instance of your class is
allowed to be passed anywhere that a parameter requires an object of
type ActionListener. This includes addActionListener() and
removeActionListener() methods.

Another widespread use is demonstrated with the List interface. Many
common structures, such as ArrayList, LinkedList and Vector, implement
this interface. This means you could create a variable of type List and
use only those methods defined in the List interface for accessing its
contents. It also means that you could decide to use an ArrayList
instead of a Vector without making changes to any exposed methods in
your class, if it's available to other classes to call.

Those are just a couple examples of its benefits that come to mind.

= Steve =
 
T

Tor Iver Wilhelmsen

This seems to be a beginner's question.

We can feel the advantages of class inheritance from at lease
sharing and reusing the super class's methods. But in an interface,
there are only abstract methods, and we have implement all the
methods in the class that implements this interface, why do we still
use interface?

Interfaces form part of the TYPE system. Any object is an instance of
exactly one class, but can be of many types: All classes in its
inheritance tree, and all implemented interfaces down that same tree.
Why don't we define the methods and write their code directly in the
class without implementing any interface or something like that?

Because then you would have to juggle e.g. two types with the same
methods instead of one type with two implementating classes. Which is
easier:

public void someMethod(SomeInterface arg) {
arg.foo();
}

or

public void someMethod(SomeClass arg) {
arg.foo();
}

public void someMethod(SomeOtherClass arg) {
arg.foo();
}

In other words, what are the advantages of using interface? I have
read some books, in which the authors just say it's a protocol and
so on.

I think the "protocol" term comes from Objective-C; Smalltalk laso
uses the word, but in a different way, as a method grouping mechanism.
I still can not understand the necessity of using interface. Can
anybody give me a sample to illustrate this?

java.lang.Comparable. Now imagine a world where that interface didn't
exist: You would need to write a sorting algorithm in a way that
either if-else if-ed all known classes with a compareTo() method, or
use reflection to ask the object's class for its compareTo() method.
 
R

Red Orchid

i recommend books related to 'Design Patterns' to you.

for example :
"[GoF] Design Patterns :
Elements of Reusable Object-Oriented Software"
... etc.


and..(as i know as)
in java, 'interface' is _only_ way for multi-inheritance.


--
Red Orchid.




(e-mail address removed) (Mary Wenge) wrote in
 
D

Dimitri Maziuk

Mary Wenge sez:

....I have read
some books, in which the authors just say it's a protocol and so on. I
still can not understand the necessity of using interface. Can anybody
give me a sample to illustrate this? Thanks.

In an ideal world interface is a contract between author of
the library and user of the library.

Textbook example: interface Sort that sorts a list. If user
code uses that interface, it does not care whether underlying
implementation is BubbleSort or QuickSort or MergeSort or
whatever. Authors of the library replace Sort implementation
in the next version and this change does not affect user code.

If, OTOH, user code calls BubbleSort everywhere, and new
version of the library comes with QuickSort instead, user
is screwed. They have to modify their code. They have to
release two versions of their program -- for people who
have new library, and for those who're stuck with the old
one. Etc.

In Java, interfaces are also used to implement multiple
inheritance. I.e. you want your FlyingCar class to
inherit from both Car and Airplane. Java won't let you
do that: you have to subclass e.g. Car and implement
Airplane, or the other way around.

Conceptually this has nothing to do with the "proper"
definition of interface as a contract (or protocol).

Dima
 
G

George W. Cherry

Mary Wenge said:
This seems to be a beginner's question.

We can feel the advantages of class inheritance from at lease sharing
and reusing the super class's methods. But in an interface, there are
only abstract methods, and we have implement all the methods in the
class that implements this interface, why do we still use interface?
Why don't we define the methods and write their code directly in the
class without implementing any interface or something like that? In
other words, what are the advantages of using interface? I have read
some books, in which the authors just say it's a protocol and so on. I
still can not understand the necessity of using interface. Can anybody
give me a sample to illustrate this? Thanks.

Merry Christmas!

Hi, Mary. It's a matter of types. Types are extremely important
in programming because they define what you can do with ob-
jects. Sometimes it's very useful to define a type that fulfills a
contract without details of its implementation, as in the type de-
fined by the Runnable interface (which requires you to write a
run() method in order to implement it). Java has four kinds of
types: classes, arrays, interfaces, and primitives. They are all
useful. The more you use Java, the more you'll like interfaces.

George
 
G

George W. Cherry

George W. Cherry said:
Hi, Mary. It's a matter of types. Types are extremely important
in programming because they define what you can do with ob-
jects. Sometimes it's very useful to define a type that fulfills a
contract without details of its implementation, as in the type de-
fined by the Runnable interface (which requires you to write a
run() method in order to implement it). Java has four kinds of
types: classes, arrays, interfaces, and primitives. They are all
useful. The more you use Java, the more you'll like interfaces.

George

(Sorry for the recursive response.) I forgot to mention the very
important feature that interfaces allow an object to be very rich
and multifaceted (polymorphic). A class can implement many
interfaces (but extend only one superclass). For example, yes-
terday I wrote a class that extends JApplet and implements
Runnable. The class could have implemented more interfaces
if I wished.

George
 
M

Mary Wenge

Thanks to everybody!

In C++, there are multiple inheritances; but in Java, a class can
inherit only one super class. In almost every Java book, interface is
introduced in just for the (similar) multiple inheritance purpose. But
I think the reason why it's useful in C++ to use multiple inheritance
is that we can reuse the **implementation** of those useful methods in
the super class. For example, if we want a new class FlyingCar, we can
inherit from classes Plane and Car, we don't need to care about how to
implement the complex method fly() in Plane, we just use it in
FlyingCar. We can feel the benefit of using inheritance. But if in
Java I define a class MyCar extends Car implements Flyable, there is
only an abstract method definition fly() in interface Flyable, I have
to implement it in my MyCar class, why do I still **inherit** it?
That's why I posted my original question.

Polymorphism is useful in design in C++. For example, if we want to
draw figures Point, Line and Circle, traditionally we can:

void fdraw (void *P)
{
switch(p->objectType)
{
case Point:
(Point *)p->draw();
break;
case Line:
(Line *)p->draw();
break;
case Circle:
(Circle *)p->draw();
break;
default: error();
}
}

There is a disadvantage: if we want to add a new figure Rectangle, we
have to update our fdraw() by adding:

......
case Rectangle:
(Rectangle *)p->draw();
break;
......

By using virtual function, it will be better. We define an abstract
super class Figure with a virtual function:

virtual void draw() = 0;

All the detailed figure classes, Point, Line, etc, inherit from it and
implement the method draw(), and then define a unique calling form:

void fdraw(Figure *p)
{
p->draw();
}

Now if we want to draw a figure, no matter what it is, we just use the
unique calling interface fdraw(), as below:

Point p(200,300);
fdraw(p);
Line l(100,200,300,400);
fdraw(l);
......


So, in my opinion, maybe the most useful feature of Java interface is
the polymorphism, or the **type**. It is not used to let you share the
implementation code in the method of a super class, it might be useful
for the derived classes to share the unique calling form of the
methods whose prototypes are defined in the super interface. So, if an
interface has only one, never another, derived class, then it seems
there is no necessity to use interface. Java interfaces are useful for
many classes which will share some common features and make the
further use of those classes easier and clearer (in code and in design
pattern). Am I right? If yes, can anybody give an example to
illustrate this?

Are there any other advantages? (If you just give me the advantages in
1 or 2 theoretic sentences, it seems a little bit hard for me to
understand.:) Some simple examples are better.)

Thanks a lot.

Mary
 
H

Harald Hein

Mary Wenge said:
Thanks to everybody!

Please take the discussion to comp.lang.java.advocacy, and also read an
archive of this group. You question (homework?) is not new at all.
 
D

Dimitri Maziuk

Mary Wenge sez:
Thanks to everybody!
.... For example, if we want a new class FlyingCar, we can
inherit from classes Plane and Car, we don't need to care about how to
implement the complex method fly() in Plane, we just use it in
FlyingCar. We can feel the benefit of using inheritance.

However, you have to hide Plane.taxi() since it does not make
much sense in flying car -- it's a car, it'll use Car.drive()
instead. If Plane.taxi() is not abstract, good luck hiding it
in FlyingCar. And you have to decide which of Car.brake() and
Plane.brake() to inherit (although in this example it's not
a difficult problem). And so on.

Dima
 
M

Michael Borgwardt

Mary said:
So, in my opinion, maybe the most useful feature of Java interface is
the polymorphism, or the **type**.

Yes, definitely.
there is no necessity to use interface. Java interfaces are useful for
many classes which will share some common features and make the
further use of those classes easier and clearer (in code and in design
pattern). Am I right? If yes, can anybody give an example to
illustrate this?

The best example has already been mentioned: Comparable, which lets you
use e.g. TreeMap or Arrays.sort() on all kinds of objects.

The most common use of interfaces is to define a "protocol" (As you
mentioned in your first posting) or "contract" that other people's
classes must fulfill in order to work with classes that you're writing,
which use those interfaces as types for their method parameters, etc.
 
M

Mary Wenge

I’m all the time looking for and asking for a not so technical
explanation or example to illustrate why we should use Java interface.
After discussing with friends here and thinking, I think I have got
one.

Think about the term “industrial standard”.

Suppose any plane should have at least 2 functions:
“taking-off” and “landing”. If you are a plane
manufacturer, it doesn’t matter you locate on an unknown island
and your plane is made of materials from the moon, as long as you want
to get an order from the public market, your plane has to provide with
at least the 2 functions “taking-off” and
“landing”. With those 2 functions, even though it looks
like a car or ox, it is a *plane*, at least a *flyable* car
(FlyingCar) or *flyable* ox. Without those functions, even though it
looks like a real “Air Force 1”, it isn’t a plane.
With this “industrial standard” or “protocol”,
another object who will interact with your product, say a pilot, will
know he/she can make the commands “take off” and
“land” to it.

So, in Movie “007”, when James is driving a car, if he is
notified that car is a new type flying car, then without any
instruction, he knows there should be a button for
“taking-off” and later another button for
“landing”. He had known that even before you produced it
or before it was taken from another planet. Because it is known as a
kind of *plane*, although it is strange, it agrees to all the contents
of “plane industrial standard”(*flyable*) --- *taking-off*
and *landing*.

Hope this will help other newbies like me who are looking for the
answers of the similar questions.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top