• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Interfaces

 
Ranch Hand
Posts: 100
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi ALL
Can someone please explain to me what an interface is and how they work.
Manybe someone has a code example ???
Thanks in advance.
 
"The Hood"
Posts: 8521
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
An interface is sort of a contract that you will do certain things.
interface JavaCoder{

abstract void writeCode();
abstract String answerJavaQuestions();
abstract void supportJavaRanch();
}

Now I know that anyone who implements JavaCoder will have AT LEAST these three behaviors (I don't need to know HOW they will do this just THAT they will do these).
Even though I do NOT know all of the classes that will eventually implement this interface I can go ahead and do certain things ahead of time. For instance:

All this can be set up ahead of time all based on the fact that I KNOW the future classes will be able to supportJavaRanch .

[This message has been edited by Cindy Glass (edited March 22, 2001).]
 
Zahid, Butt
Ranch Hand
Posts: 100
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi ALL
Excellent answer Cindy, Just what I expected from you
Just to confirm then, Do you "have" to declare all methods in the Interface as "abstract", and therefore you have to "override" them in a class that implements the interface ???
Or can an Interface declare methods other than abstract ??
Are interfaces used to implement " Multiple Inheritance "
in Java ???
Thanks in advance.
 
Sheriff
Posts: 7001
6
Eclipse IDE Python C++ Debian Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Interface methods are abstract by default, so you don't need to declare them as such. A class which does not provide implementations for all the methods in an interface cannot be said to "implement" the interface.
Interfaces can be used to accomplish some of the same jobs which multiple inheritance is used for in other languages.
 
Zahid, Butt
Ranch Hand
Posts: 100
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi ALL
Thnks for your answer Frank.
Has anyone got anything else to add ??
Thanks, Zahid.
 
Frank Carver
Sheriff
Posts: 7001
6
Eclipse IDE Python C++ Debian Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I would like to add that I consider it good style to use a *lot* of interefers to an interface, so I can vary implementations at will. For example:

Things to note:
1. The variable "data" is of type List (an interface in java.util) By using an interface here, I can "plug-in" any class which implements List, such as ArrayList, Vector, or one I wrote myself with no other changes to the code.
2. The list contains items of type MyThing (an interface of mine), so that it can contain any mixture of SimpleMyThing and ArrayMyThing classes or any other classes which implement the interface. I tend to do this even if there is only one class at the moment which implements the interface. Using an interface helps a reader understand exactly which methods are used by the using class, and know that any others are free to be refactored as appropriate. Using an interface also lets me simply write "dummy" or "stub" versions of classes for testing purposes.
3. the variable "it" is of type Iterator (an interface in java.util).
This is only a small program fragment, but makes large use of interfaces, and to good effect.
I often wish that the original Java designers had made more use of interfaces. We had to wait for the Java 2 collections to get sensible use of interfaces for basic data structures, and I think it is a real shame that Throwable is not an interface.
Oh Well...

[This message has been edited by Frank Carver (edited March 22, 2001).]
 
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
A point that may be worth mentioning here is that interfaces really come in handy down the road especially when they are incorporated into the early design stages of a given application or api.
Also, remember that interfaces are Java's way of effectively implementing the idea of multiple inheritance.
Ie, if MyPet class has the characteristics and methods of WildCanine as well as the characteristics and methods of being Trainable, I cannot subclass both WildCanine and Trainable classes to make MyPet. I can however make MyPet implement the WildCanine and Trainable interface, and make sure that MyPet will behave as a WildCanine and a Trainable object. Then, I can plug MyPet in places that require a WildCanine and/or a Trainable object.
Hopefully this adds a little and doesn't repeat the above discussion too much.
OP
 
Cindy Glass
"The Hood"
Posts: 8521
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Nicely put.
 
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Zahid,
Here is a definition of an interface that I think is pretty good. It is taken from Ivor Horton's Beginning Java2(pg 272). I
think this is one of the best books for beginners:
"An interface is essentially a collection of constants and
abstract methods. . .you implement the interface in a class-
that is, you declare that the class implements the interface
and you write the code for each of the methods declared in
interface as part of the class definition. When a class
implements an interface, any constants that were defined
in the interface definition are available directly in the
class. . . Methods in an interface are ALWAYS public, static
and final."
Hope this helps.
 
Cindy Glass
"The Hood"
Posts: 8521
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
FINAL???
From the JLS:


Note that a method declared in an interface must not be declared final or a compile-time error occurs. However, a method declared in an interface may be
implemented by a method that is declared final in a class that implements the interface.


and


Note that a method declared in an interface must not be declared static, or a compile-time error occurs, because static methods cannot be abstract.


however


For compatibility with older versions of the Java platform, it is permitted but discouraged, as a matter of style, to redundantly specify the abstract modifier for methods
declared in interfaces.
It is permitted, but strongly discouraged as a matter of style, to redundantly specify the public modifier for interface methods.



[This message has been edited by Cindy Glass (edited March 23, 2001).]
 
Ranch Hand
Posts: 411
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
All these definitions of interfaces are great but one question I've always had is; when would it be a good idea to actually use one? If I'm writing an application why should I write an interface to force me to use the methods when I could just write a class that invokes the methods anyway? Perhaps if I had a better knowledge of system architecture this would be plain to me.
An example would be great. I've seen examples that simply show interfaces in use but it still doesn't answer my question. When would you write an interface as opposed to a class?
Thanks for any help!
Paul
 
Cindy Glass
"The Hood"
Posts: 8521
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
To quote the famous bartender Thomas Paul . . . (I stole this post out of Advanced )


The funny thing is that inheritance is one of the easier aspects to understand and yet the one that you should probably code with the least. "Design Patterns" second principle of OOD is "favor object composition over class inheritance". As it says, "Inheritance breaks encapsulation." Inheritance causes a tight coupling between the parent and child classes which violates OO. The goal should be to inherit interfaces and not implementations. There is of course a tradefoff since an application built around object composition will have more objects.


So according to this answer, always try to use interfaces first.
In addition, you can only extend one class. If you have more than 1 set of behaviors that you want to implement you HAVE to use interfaces. Of course you could give your class the same methods as the interface defines without implementing the interface, but then you loose the object oriented benefits, like being able to put your class into a variable that has the TYPE of the interface, or casting your class into the interface, etc.

 
Paul Bull
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
OOPS,
I think I skipped over some key points in the quote I posted last night. Thank you Cindy for the clarification.
 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Paul Keohan:
All these definitions of interfaces are great but one question I've always had is; when would it be a good idea to actually use one? If I'm writing an application why should I write an interface to force me to use the methods when I could just write a class that invokes the methods anyway? Perhaps if I had a better knowledge of system architecture this would be plain to me.
An example would be great. I've seen examples that simply show interfaces in use but it still doesn't answer my question. When would you write an interface as opposed to a class?
Thanks for any help!
Paul


well here's what i think is when to use interface
now they r designed to support dynamic method compilation at run time. normally, for a method 2 b called from one class to another,both classes needed 2 b present at compile time so that the java compiler ca check to ensure that the method names are compatible. but with interfaces since they are in different heirarchy from classes, it is possible for classes that are unrelated in terms of the class heirarchy to implement the same intrerface i.e. the method 2 b executed is looked up dynamically at run time, allowing classes to be created later than the calling method. the called function can dispatch through an interface without having to know anything about the calling function.
 
Paul Keohan
Ranch Hand
Posts: 411
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks for the response but I'm afraid I can only read English. What's all this "r" and "2 b" crap? Please write properly or don't write at all. Also, words at the beginning of a sentence start with a capital letter.
 
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
A good and small example here would give the importance of using an interface....
abstract class Vechicle
{
}
class Car extends Vehicle
{
}
class Taxi extends car
{
}
class Horse
{
}
If I have a method say speed() is applicable to all classes mentioned above.
So if I declared that in the Vechicle, this cannot be inherited by Horse (eventually it also has speed()) because its a different class.
So now to get this feature, I define an interface called Traffic which has this method speed() and other methods related to traffic.
And all the above classes can implement this interface, since they are part of the traffic.
I the code would look like this....
interface Traffic
{
public void speed();
.....
.....
}
abstract class Vechicle implements Traffic
{
}
class Horse implements Traffic
{
}
Here I've not mentioned this for Car and Taxi, why?
Since they are inherited from Vehicle, they get this method from class Vehicle.
Excuse me if I'd repeated anything too much.
Cheers
Siva
 
Ranch Hand
Posts: 177
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I wrote a lengthy explaination of interfaces in response to another post. See: http://www.javaranch.com/ubb/Forum1/HTML/001108.html
 
Paul Keohan
Ranch Hand
Posts: 411
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This is a good description but it still brings me back to the same question. The interface doesn't give you the actual code so what is the advantage? Why not just write speed() methods for each of the other classes? Your description is to write an interface that will make me have a speed() method in all implementing classes. Why? My speed() method in Car might calculate the speed of travel. My speed() method in Horse might display a green carrot to the screen.
Paul

Originally posted by Siva Prasad:
A good and small example here would give the importance of using an interface....
abstract class Vechicle
{
}
class Car extends Vehicle
{
}
class Taxi extends car
{
}
class Horse
{
}
If I have a method say [b]speed()
is applicable to all classes mentioned above.
So if I declared that in the Vechicle, this cannot be inherited by Horse (eventually it also has speed()) because its a different class.
So now to get this feature, I define an interface called Traffic which has this method speed() and other methods related to traffic.
And all the above classes can implement this interface, since they are part of the traffic.
I the code would look like this....
interface Traffic
{
public void speed();
.....
.....
}
abstract class Vechicle implements Traffic
{
}
class Horse implements Traffic
{
}
Here I've not mentioned this for Car and Taxi, why?
Since they are inherited from Vehicle, they get this method from class Vehicle.
Excuse me if I'd repeated anything too much.
Cheers
Siva[/B]


 
Ranch Hand
Posts: 3695
IntelliJ IDE Java Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I remember having (and sometimes I still do) the same complaints when I was trying to "roll my own inheritance" in Visual Basic. Sure, you can have interfaces, but that was @($@)(*&%@ stupid, because it was interface inheritance, and not implementation inheritance.
Well anyways... My breakthrough came when I stopped thinking of interfaces as ways to
a. not write so much code
b. simulate inheritance
The major advantage (from my viewpoint) of interfaces, is that it contractually obligates the implementer to provide certain behaviour. The enforcer of the contract is the compiler. If you want your class to have the behaviour of "Traffic", then yes, you *must* produce code that implements all of the interface. Interfaces are not about saving typing.
The advantage of the contractual obligation is buried in that mess (I would've been nicer though) that pryti wrote. At some point much later on, lets say your class takes part in some vast collection of objects (more about this latter).
Since Java does not have multiple inheritance, and because at a certain point in class trees, classes can come from very divergent heirarchies, it's impossible using single inheritance to produce all the behaviour you might want in an object... but you *can* implement more than one interface. And as the previous post suggests, sometimes it wouldn't make sense to multiply inherit. A Horse is *not* a vehicle. And yet, you want the horse to have a few things in common with vehicles. The answer is an interface.
That way, when cars and horses are in the vast collection I spoke of earlier, you can use an interface reference, call the method "speed" and be *guaranteed* that it will not result in a runtime dynamic resolution catastrophe.
Bottom line though.... bend you mind around that fact that interfaces are not really about saving typing or inheritance. As soon as I did, my head stopped hurting.
 
mister krabs
Posts: 13974
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Paul Keohan:
This is a good description but it still brings me back to the same question. The interface doesn't give you the actual code so what is the advantage?


Because you can write generic methods that can handle any Traffic object as an input paramter. Otherwise you would have to have a sepoarate method for Horse and Vehicle:
public void setSpeed(Traffic traffic) {
traffic.speed();
}
You can put Horse and Vehicle objects in the same array:
Traffic[] traffic = new Traffic[10];
// load array with Horse and Vehicle objects
for (int i=0; i < traffic.length; i++)
traffic[i].speed();

[This message has been edited by Thomas Paul (edited March 28, 2001).]
 
reply
    Bookmark Topic Watch Topic
  • New Topic