LinuxQuestions.org
Download your favorite Linux distribution at LQ ISO.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 08-23-2006, 10:36 AM   #1
joelhop
Member
 
Registered: Mar 2004
Location: Pennsylvania::USA
Distribution: Fedora Core 6
Posts: 100

Rep: Reputation: 15
Question How to use an Interface?


I am getting my feet wet in OO Programming, and have run into the idea of an Interface in both Php and Java. I get the basic idea about Inheritance:

"Inheritance" a subclass has exactly one superclass in an "is-a-relationship".
example: VW Bug is a Car.

I get that, and you use extends to implement it, like Class VwBug extends Car and you get all the state and method goodies from Car without duplicating, and then provide custom state and method goodies for the specific sub-class VwBug to make it a unique type of Car.

I'm struggling with the idea of an Interface though, I understand the idea is that unlike in Inheritance, a class can fulfill more than one "is-a-relationships".

I'm just having trouble thinking of an example of how to describe this, or why you would use this instead of Inheritance?

Thanks for any examples, links, opinions!

-KARL
 
Old 08-23-2006, 01:16 PM   #2
joelhop
Member
 
Registered: Mar 2004
Location: Pennsylvania::USA
Distribution: Fedora Core 6
Posts: 100

Original Poster
Rep: Reputation: 15
I found this example:

Interfaces are used to collect like similarities which classes of various types share, but do not necessarily constitute a

class relationship. For instance, a human and a parrot can both whistle, however it would not make sense to represent

Humans and Parrots as subclasses of a Whistler class, rather they would most likely be subclasses of an Animal class

(likely with intermediate classes), but would both implement the Whistler interface.

Can anyone show me how this would be implemented in either java or php?
 
Old 08-23-2006, 01:31 PM   #3
xhi
Senior Member
 
Registered: Mar 2005
Location: USA::Pennsylvania
Distribution: Slackware
Posts: 1,065

Rep: Reputation: 45
yeh you have the right idea with that example you posted there. an interface will allow a group of unrelated classes to be seen as related based on their behavior and not on their inheritance heirarchy.. good thing to pick up right away in java, since you are restriced from using multiple inheritance, you have to use interfaces. i would rather works with interfaces 90% of the time anyhow..

here is an example but ill warn you that this seemed clearer in my head before i put in on paper. see if you follow.
Code:
class GameObject{}

class Player
{
    void punch(GameObject o)
    {
        if(o instanceof Smashable)
            o.smash();
    }
}

interface Smashable
{
    void smash();
}

class Window extends GameObject implements Smashable
{
    void smash()
    {
        System.out.println("smashed window");
    }
}
class Brick  extends GameObject{}

main()
{
   Window w;
   Brick b;
   Player p;

   p.punch(w);  // window smashed
   p.punch(b);  // hand broke :)
}
(btw this may not be syntactically correct. i didnt test it i just typed it in here)
 
Old 08-23-2006, 01:57 PM   #4
joelhop
Member
 
Registered: Mar 2004
Location: Pennsylvania::USA
Distribution: Fedora Core 6
Posts: 100

Original Poster
Rep: Reputation: 15
What if I also wanted a smashable door? How would that modify the code?

Would class Door also extend GameObject and implement Smashable? How would class Door look?
 
Old 08-23-2006, 02:06 PM   #5
xhi
Senior Member
 
Registered: Mar 2005
Location: USA::Pennsylvania
Distribution: Slackware
Posts: 1,065

Rep: Reputation: 45
it would look just like window, except its a door

Code:
class Door extends GameObject implements Smashable
{
    void smash()
    {
        System.out.println("smashed door");
    }
}
you could say that you have an openable interface as well. and it might look something like this

Code:
class GameObject{}

class Player
{
    void punch(GameObject o)
    {
        if(o instanceof Smashable)
            o.smash();
        else
          System.out.println("Ouch!");
    }
    void open(GameObject o)
    {
        if(o instanceof Openable)
           o.open();
        else
           System.out.println("It wont open");
    }
}

interface Smashable{void smash();}
interface Openable{ void open();}

class Door extends GameObject implements Smashable, Openable
{
    void smash(){ System.out.println("smashed door"); }
    void open() { System.out.println("opened door"); }
}

class Window extends GameObject implements Smashable, Openable
{
    void smash(){ System.out.println("smashed window"); }
    void open(){ System.out.println("opened window"); }
}
class Brick  extends GameObject{}

main()
{
   Window w;
   Brick b;
   Player p;

   p.punch(w);  // window smashed
   p.punch(b);  // hand broke :)
}
 
Old 08-23-2006, 02:09 PM   #6
xhi
Senior Member
 
Registered: Mar 2005
Location: USA::Pennsylvania
Distribution: Slackware
Posts: 1,065

Rep: Reputation: 45
actually i just noticed in my example, you are going to need to cast the GameObject to the appropriate interface object before calling the interface functions.

ex.
Code:
void punch(GameObject o)
{
    if(o instanceof Smashable)
            ((Smashable) o).smash();
    else
          System.out.println("Ouch!");
}
 
Old 08-23-2006, 02:18 PM   #7
joelhop
Member
 
Registered: Mar 2004
Location: Pennsylvania::USA
Distribution: Fedora Core 6
Posts: 100

Original Poster
Rep: Reputation: 15
I think I am starting to see what you are saying.

Both Door and Window implement the Smashable interface which calls the method smash(), meaning that both the Door and Window Classes must include a method smash(), however the actual smash() method itself within the Door and Window classes can vary as seen in:

void smash(){ System.out.println("smashed door"); }
void smash(){ System.out.println("smashed window"); }

Do I understand the rules correctly so far?

It would seem the purpose of the interface is simply to tell the class to execute methods found within it? As in your example, class Door extends GameObject implements Smashable if you removed the implements Smashable, the class wouldn't know to run the smash() method.

Is there something more to interfaces that I am missing?
 
Old 08-23-2006, 02:28 PM   #8
joelhop
Member
 
Registered: Mar 2004
Location: Pennsylvania::USA
Distribution: Fedora Core 6
Posts: 100

Original Poster
Rep: Reputation: 15
interfaces

I think this part may be a bit over my head:

void punch(GameObject o)
{
if(o instanceof Smashable)
((Smashable) o).smash();
else
System.out.println("Ouch!");
}

Can you give me a basic idea of the program flow?


I see the result will either be "Ouch" or _____ Broken but I'm just not sure about this part:


void punch(GameObject o)
{
if(o instanceof Smashable)
((Smashable) o).smash();

How you are executing that, passing variables to it, and what exactly is going on in the if.
 
Old 08-23-2006, 02:32 PM   #9
xhi
Senior Member
 
Registered: Mar 2005
Location: USA::Pennsylvania
Distribution: Slackware
Posts: 1,065

Rep: Reputation: 45
yeh my example is lacking a bit. ill try another way for a bit

so with an interface you can also make completely different objects seem like they are the same by using an interface. they can come from completely unrelated object heirachies and still be treated as the same. a good example would be java's Printable interface.

you can take any object and have it implement Printable, and then it is possible to pass it to the print methods.. so you could take the Door class that was in the earlier example, or some other class such as a custom container you make and if you implement printable, you can treat that object as a Printable object and pass it to the printer. and the printer object will call the Print that is defined because you implemented Printable and generate what you want printed for that object.

interfaces just make polymorphic objects bend a little further. one of those things that until you see a really great use for it and you go "Ahaa!" then it is really hard to try to explain. but it would probably be helpful to lookup Printable interface and mess with it a while.
 
Old 08-23-2006, 02:36 PM   #10
xhi
Senior Member
 
Registered: Mar 2005
Location: USA::Pennsylvania
Distribution: Slackware
Posts: 1,065

Rep: Reputation: 45
Code:
void punch(GameObject o)
{
    if(o instanceof Smashable)
       ((Smashable) o).smash();
}
that says that if o is a Smashable object, then call o's smash method. the
((Smashable) o)
part is to cast o from a GameObject to a Smashable (because a GameObject knows nothing about smash())
 
Old 08-23-2006, 02:41 PM   #11
joelhop
Member
 
Registered: Mar 2004
Location: Pennsylvania::USA
Distribution: Fedora Core 6
Posts: 100

Original Poster
Rep: Reputation: 15
Yeah cause right now interfaces seem like a pretty big waste of time. Web resources are pretty limited as well, been browsing for a few hours now. For instance the java tutorial explanation:

interface Bicycle {

void changeCadence(int newValue);

void changeGear(int newValue);

void speedUp(int increment);

void applyBrakes(int decrement);
}

class ACMEBicycle implements Bicycle {

// remainder of this class implemented as before

}

And that's literally all they say about it, except on the last section of this tutorial, it has an exercise to create interfaces, although it never specified how.

wtf? ;p

This is the tutorial I'm refering to:

http://java.sun.com/docs/books/tutor...interface.html

Last edited by joelhop; 08-23-2006 at 02:46 PM.
 
Old 08-23-2006, 02:45 PM   #12
xhi
Senior Member
 
Registered: Mar 2005
Location: USA::Pennsylvania
Distribution: Slackware
Posts: 1,065

Rep: Reputation: 45
heh. makes me feel better about my examples..

if you can do some printing in java, i think you would definately understand interfaces.

http://java.sun.com/docs/books/tutor.../overview.html
 
Old 08-23-2006, 02:49 PM   #13
joelhop
Member
 
Registered: Mar 2004
Location: Pennsylvania::USA
Distribution: Fedora Core 6
Posts: 100

Original Poster
Rep: Reputation: 15
I'll be checking that out, it's part of the same series of tutorials I'm on. I'm just surprised they would introduce a concept so early in the tutorial and request an exercise without even explaining it, their page on interfaces is seriously lacking. Although so is the rest of the web, I can't seem to get a straight answer from any site about the actual advantage, or purpose of using "implements"

I keep hearing that: Interfaces provide a form of multiple inheritance. But I am unable to find any examples of any class doing this.

Last edited by joelhop; 08-23-2006 at 02:53 PM.
 
Old 08-23-2006, 03:00 PM   #14
xhi
Senior Member
 
Registered: Mar 2005
Location: USA::Pennsylvania
Distribution: Slackware
Posts: 1,065

Rep: Reputation: 45
> I keep hearing that: Interfaces provide a form of multiple inheritance. But I am unable to find any examples of any class doing this.

yes, implementing interfaces is the only type of multiple inheritance java allows.

as for an example of classes doing this, there are tons. if you browse around the java docs you will see many. one common is an ArrayList
 
Old 08-23-2006, 03:05 PM   #15
joelhop
Member
 
Registered: Mar 2004
Location: Pennsylvania::USA
Distribution: Fedora Core 6
Posts: 100

Original Poster
Rep: Reputation: 15
That sounds a lot like the microsoft doc I just finished reading for interfaces in VB:

When to Use Interfaces

Interfaces are a powerful programming tool because they allow you to separate the definition of objects from their implementation. Interfaces and class inheritance each have advantages and disadvantages, and you may end up using a combination of both in your projects.
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
MASQUERADE only one interface GeoSava Linux - Networking 8 02-03-2006 09:36 AM
Interface up but no IP, need help! Scyphon Linux - Wireless Networking 4 11-08-2005 06:51 PM
Powering up Interface TMH Linux - Networking 3 02-26-2005 06:07 PM
which interface jag2000 Linux - Newbie 4 04-13-2004 06:41 PM
Graphical Interface pazvant Red Hat 1 11-19-2003 07:49 AM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 10:12 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration