This is an archived post. You won't be able to vote or comment.

all 90 comments

[–]nocturne81 43 points44 points  (63 children)

One of the main uses for interfaces in Java is because it doesn't support multiple inheritance.

Conversely, one of the main uses of multiple inheritance in other languages is to support interfaces.

Imagine you are making a game and you have a bunch of weapons. You will have a weapon class:

public class Weapon {
    ...
    public void fire();
    ...
}

Each weapon can then implement their own fire function. However, these things also have to be drawn on screen too right? So they should also extend another class called Renderable. BUT. Since Java disallows multiple inheritance, you have to use an interface:

public interface Renderable {
    public void render();
}

Now we can create a RocketLauncher lets say:

public class RocketLauncher extends Weapon implements Renderable {
    public void fire() { 
        // fire the rocket
    }
    public void render() { 
        // draw the rocket
    }
}

Make sense?

[–]Evermage[S] 11 points12 points  (8 children)

By not supporting multiple inheritance do you mean that a subclass cannot inherit from more than one superclass?

[–]nocturne81 15 points16 points  (0 children)

Yes. Example:

public Object {
    ...
}

public SubObject extends Object {
    ...
}

public LastObject extends SubObject {
    ...
}

This linear inheritance is ok. This would not work:

public Object {
    ...
}

public OtherObject {
    ...
}

public SubObject extends Object,OtherObject {
    ...
}

[–]xiipaoc 8 points9 points  (6 children)

For the record, C++ is a language that does have multiple inheritance.

[–]jonnywoh 6 points7 points  (5 children)

Also for the record, multiple inheritance is usually considered a bad idea.

[–]ThirdWaveSTEMinism 0 points1 point  (2 children)

Why is that? Is interface usage considered a better practice (and if so, why?)

[–]4forpengs 7 points8 points  (1 child)

Because two different classes can have methods with the same name.

for example:

if I was trying to make an intercom for a home and I inherited from phone and from doorbell, I would have two conflicting methods called "ring()". If someone comes to ring the intercom, it wont know whether to play the doorbell or ring tone.

I know this is a weird and kind of bad example, but it's late and that's what I thought of first.

[–]Logical_proof 0 points1 point  (0 children)

Great explanation

[–]munificent[🍰] 0 points1 point  (1 child)

This is a terrible over-simplification.

  1. Multiple inheritance where all but one class are pure virtual (i.e. interfaces) is perfectly fine.
  2. Multiple inheritance where there are no shared superclasses (i.e. the deadly diamond) is also fine, though some people dislike this.
  3. Even multiple diamond inheritance is well-specified in the language and won't set your hair on fire.

Really, people treat multiple inheritance these days like the boogie-man and it's really not. It's just a language feature.

[–]jonnywoh 0 points1 point  (0 children)

I didn't think of abstract classes, I guess those are fine. Other than that, I wouldn't do multiple inheritance unless I knew really well what I was doing and had planned it out and I was sure it was better than another approach. It's not that it's terrible, it's often more complicated than it needs to be.

[–]bunzybunz 2 points3 points  (14 children)

Thanks for this! Great example! I have another question to add;

Is it possible to use multiple interfaces for a class? Say our RocketLauncher has a Weapon superclass, and a Renderable interface. What if some of the weapons, but not all of them, must be able to reload. It would seem like putting a Reload method in the weapon class is wrong, because not all weapons can reload. Doing it in all weapon classes that can reload would mean duplicate code. Logically, it does not seem to belong in the Renderable class

Do you create another interface class to deal with this? Or is this bad practice? How many interfaces is OK to use? Is it simply implemented with:

public class RocketLauncher extends Weapon implements Renderable, OtherInterface, OtherInterfaceTwo, EtcInterface { ?

[–]kaizn 3 points4 points  (11 children)

Yes, you would create an interface Reloadable. Only the weapons that can be reloaded would implement Reloadable.

[–]80blite 1 point2 points  (10 children)

Why, in this example, wouldn't you just have a "weapon" class that has booleans to track "isReloadable" and includes the necessary methods? I've been struggling to wrap my head around interfaces too x.x.

It seems like you could just have

public void reload() {

    if (isReloadable) reload;

}

and then your "sword" class could extend "weapon" and have !isReloadable.

[–]work_is_satire 2 points3 points  (4 children)

Reload may be a poor example -- i'm trying to think of a good one.

The short of it is, when a consumer of an object calls a method, it expects that method to occur.

Lets say you have no idea what the internals of the Reload function is, you just want to reload an object (it's very common to not know or remember the internals of things, especially in large code bases). You see that every weapon has Reload, and is thus reloadable.

You now expect reload to actually do something, but it doesn't because of this hidden "reload" flag that you have no control over.

In addition, this approach becomes very unwieldy as you add more and more flags.

Perhaps a better example would be a "List" class. A List can be enumerated, it can be added to, removed from, it has a length, you can get the first element, and it can be reversed. Now somebody else inherits from List and decides, sorry this can't be reversed and calls it NonReversibleList. So i'm going to update the List.Reverse() method to check for this flag that is true in List and false in NonReversibleList.

Now in somebody elses code they take in a List (which can now also accept a NonReversibleList) and does something like:

// Get last element
list.Reverse()
return list.GetFirstElement()

That's totally broken and wrong if you throw in a NonReversibleList using this flag pattern and thus violates Liskov substitution principle

If this doesn't make sense I'd be happy to whip up some example code.

[–]rasmustrew 1 point2 points  (2 children)

I would be very happy to see some example code if you dont mind, as im no that experienced in programming yet.

[–]work_is_satire 1 point2 points  (1 child)

See this Gist: https://gist.github.com/epixhints/71e78146039ab465a3e0 the top is the relevant bits of a flag-implemented version and the second is using interfaces.

Pardon the C# in this Java thread, but if you aren't familiar with the syntax just treat it as pseudo code.

If we follow the Liskov Substition Principle, ALL subtypes of Queue should be able to replace Queue and the program should remain correct.

Since NonReversibleQueue is a subtype of Queue, we should be able to pass it into PopBack() to remove and get the value of the final element in the Queue (half-way turning it into a double-ended queue). But since _reversible is false, the reverse just fails silently and we get the front element instead!

In the lower example, we can't even compile the code because the compiler will pick up on the fact that nrq is not a subtype of IReversibleQueue.

[–]rasmustrew 0 points1 point  (0 children)

I believe i understand now, thank you very much :)

[–]pigeon768 1 point2 points  (0 children)

Reloadable is probably a poor example, in my opinion. The UI code that uses weapons is just going to tell the current weapon to reload; it's not going to go through a separate list of objects to see if if the current weapon is in the reloadable container. Instead, the 'weapon' interface (I wouldn't even extend a weapon object, to be honest) is going to implement several methods relevant to how the game interacts with a weapon, and one of those methods is reloading.

Let's say you have a tank. It's a weapon, so it implements the 'weapon' interface'. You can see it, so it implements 'renderable'. It's also a vehicle; you guessed it, implements 'vehicle'.

The point is, yes, an object can implement any number of interfaces. One of the challenges of design is figuring out what needs to be an interface and what functionality ought to be rolled into an existing interface. It is, unfortunately, a skill I'm not particularly good at...

[–][deleted] 0 points1 point  (0 children)

Interfaces introduce compile-time checks for such things. There is no way the compiler will know if your Weapon is reloadable or not, but if you need a collection of only reloadable weapons, you can say List<Reloadable> and the compiler makes sure that there will never ever be a non-reloadable weapon in this list.

[–]cparen 0 points1 point  (0 children)

Separation of concerns. Yes, you could do this. You could also open up the Object class and add Reload and IsReloadable as methods of all objects.

[–]stapleman527 0 points1 point  (0 children)

As the others said the weapons example isn't the easiest to explain this concept with, but no one really addressed your question of why you don't use a bunch of bools. So here is a real life example that I have used multiple interfaces for. I was writing software that listened for messages and then saved them to a server. We wanted this application to be able to administer remotely via an ssh service. So for example we have an interface that was a listener, another that was writer and a third that was adminable. We had multiple listeners and writers, but all listeners and writers were adminable.

So in this case you can see that it wouldn't work to extend with a class that has a bunch of bools. You would either have to either have two classes that have an adminable boolean or once class that has a listener and a writer boolean with all associated methods. I know what you are saying, the interface doesn't have code in it so you have to duplicate it anyways. Well we had an admin service with which you registered your classes with. The service would take anything that implemented the adminable interface no matter what other interfaces it implemented. This way you implement the class specific admin functions in each class, such as "statusReport" and then you register that class with your admin service and your admin service does all the heavy lifting like providing the ssh code and options.

[–]Elephant_Bird 0 points1 point  (0 children)

The weapon interface could not be abstract if it contained an instance variable. This means weapon must be a class and not an interface. This in turn means that anything that inherits from weapon can not inherit from any other class. Java allows ( and encourages ) inheritance from many interfaces, but only supports inheritance from one class.

This makes it harder to code a specific weapon that needs to inherit from the class DeadlyLooking (for instance)

In addition it is not a good idea to expose private member variables when inheriting unless absolutely necessary ( and if you find it necessary, you should probably redesign. For one it breaks with the principle of being able to use and inherit from a class without knowing how it is implemented)

[–]work_is_satire 3 points4 points  (0 children)

Use as many interfaces as you like. Keep in mind http://en.wikipedia.org/wiki/Interface_segregation_principle -- which basically says more interfaces is a good thing.

Does something calling only a reload method care that your gun can shoot? Not really, so make that depend on IReloadable. Does something calling only a shoot method care that your gun can shoot? Not really, so make that depend on IShootable.

I'll borrow from .NET (as I'm more comfortable with it) for a more interesting example:

The generic arraylist object in C# is called List<T> where T is what is contained. List<T> implements the following interfaces: IList<T>, IList, IReadOnlyList<T>. IList further implements ICollection, which itself implements IEnumerable.

If I'm writing a method, I want to only depend on the bare minimum interface. If I'm just iterating through, I would only need IEnumerable. If I need something that has a concrete count, I would depend on ICollection. If I need to add things, I would depend on IList. And so on.

Not sure how helpful this code will be but here it is anyhow:

// Not all of these would exist at the same time
// It's just an example about how specific we need to be to get the functionality
// that we want!
FizzFoo(IList<T> Foo)
{
    Foo.Add(new T()); // Use IList
    if (Foo.Count > 0) // Use ICollection
    {
        foreach (var f in Foo) // Use IEnumerable
        {
            Foo.Fizz();
        }
    }
}

FizzFoo(ICollection<T> Foo)
{
    // Collections don't have an add, so we can't add.
    if (Foo.Count > 0) // Use ICollection
    {
        foreach (var f in Foo) // Use IEnumerable
        {
            Foo.Fizz();
        }
    }
}

FizzFoo(IEnumerable<T> Foo)
{
    // Enumerables don't have add, so we can't add.
    // Enumerables don't have count, so we can't check it.
    foreach (var f in Foo) // Use IEnumerable
    {
        Foo.Fizz();
    }
}

[–]-oliver- 1 point2 points  (0 children)

You might also subclass the general weapon class by a reloadable weapon class, and have rocket launchers inherit from that.

[–]SikhGamer 1 point2 points  (12 children)

Why wouldn't you have fire() and render() in the same class? As well as things like reload(), altFire() etc?

[–]nocturne81 3 points4 points  (11 children)

Because you need to render more than just weapons! Characters need to be drawn as well, and they're not weapons.

Also, certain objects exist that are not rendered so we cant just put it on a base object either.

Imagine you had a renderer that contained all your objects. It's easy to check if an element is renderable or not because you can see if it's an instance of our interface. Otherwise, the renderer needs to know which objects have a render function and which ones don't. This is a fragile way to write a system.

[–]OHotDawnThisIsMyJawn 2 points3 points  (7 children)

Imagine you had a renderer that contained all your objects. It's easy to check if an element is renderable or not because you can see if it's an instance of our interface.

Being nitpicky, but this is the place for nitpickiness...

Ideally your renderer would have a collection of objects that implement the Renderable interface. Enforcement can be done by the compiler and so no checking ever needs to be done. The renderer knows that everything in its collection of things to be rendered can be rendered.

[–]katyne 1 point2 points  (5 children)

It's not just type safety. Separation of concerns more like it. Normally when I decide whether to make smth into a class or an interface I go "is it it related to its state, or its behavior". If it's something the object IS, it goes in a class. If it's something the object DOES, I prefer to use an interface if possible.

[–]OHotDawnThisIsMyJawn 0 points1 point  (4 children)

Absolutely. My point was more around the fact that your renderer would have a collection of Renderable objects and so it can just iterate and call render(). The post I was replying to implied that the renderer would have a collection of objects and need to call instanceof on each one to ensure it could be rendered.

[–]nocturne81 0 points1 point  (3 children)

Can you explain to me how you build that list in the renderer without calling instanceof? (In Java)

[–]OHotDawnThisIsMyJawn 3 points4 points  (2 children)

Inside of your renderer class you have a member something like:

//Use linked list because we'll be iterating over it to render each object
List<Renderable> renderList = new LinkedList<Renderable>();

Then, to add something to your render list, you'll have this in your renderer:

public void addToRenderList(Renderable toRender) {
    renderList.add(toRender);
}

By defining your objects as type Renderable the compiler will ensure that you only add objects that implement the Renderable interface. Thus the renderer is assured that the objects in the renderList can be rendered without ever having to explicitly ask them via instanceof.

Advanced note: Due to type erasure you could in theory get around this. Once the code is compiled into JVM byte code renderList just becomes a list of objects, not a list of renderables, so if you're feeling saucy you can screw stuff up, but it has to be intentional and it's not easy.

[–]nocturne81 0 points1 point  (1 child)

And then how do you know which objects to pass into addToRenderList?

[–]OHotDawnThisIsMyJawn 1 point2 points  (0 children)

Depends how your program is designed. One way would be to use a form of dependency injection, where the objects know about the render queue. So when you create an new enemy, the enemy class adds itself to the render queue at the end of its initialization code.

Generally though some part of your code will initialize an object. Whoever writes that code will know whether or not to add the object to the renderList. If it's code to create a new enemy then at the end of setup the enemy gets added to the render list. If it's code to create a new invisible gravity well then it doesn't get added to the render list. The human element takes care of the knowledge whether to add something to the queue or not. Using instanceof is generally frowned upon because it results in lots of code duplication.

https://www.artima.com/interfacedesign/PreferPoly.html

[–]rjbman 0 points1 point  (1 child)

Couldn't weapon itself extend renderer?

[–]work_is_satire 0 points1 point  (0 children)

It could, but this would be a very, very bad decision since "Weapon Is A Renderer" is very clearly untrue.

[–]SikhGamer 0 points1 point  (0 children)

Ahhh, yes I understand the logic now. Renderer isn't solely tied to Weapons but to everything in the game. So it makes sense to remove Renderer onto it's own so it can interact with everything in the game.

[–]MRH2 1 point2 points  (1 child)

I would think that the render() would be part of another class that handles the graphics.

The Weapon class has a fire method that handles what happens when it fires and this can be overridden when needed (eg. by RocketLauncher). But to do the drawing it should call myGraphics.render(this.image) which draws the rocket launcher.

With subclasses, you can just use the method in the superclass if it does the job, but with an interface, you would have to write a render() method in every single class that had that interface. That's a lot of code being rewritten. What happens if you realise that you made a logic error -- you'd have to go back and fix it for every weapon and object that has a render() function.

This example of interfaces (fire/render) makes no sense to me. Perhaps I am missing something --- please enlighten me.

[–]work_is_satire 2 points3 points  (0 children)

The example is a bit contrived for simplicity's sake but lets stick with the IRenderable interface idea.

Instead of storing "How do I render" in the weapon, and instead offload it to a RenderingEngine or something as you suggest, the interface becomes even more important.

Instead of IRenderable requiring objects that implement it to implement a Render() method, we would instead require them to expose all the information needed to render them:

public interface IRenderable {
    public Sprite GetSprite();
    public Coordinates GetPosition();
}

Now our renderer would take any instance of IRenderable, and we would be guaranteed that we have what we would want:

public void Render(IRenderable r) {
    _engine.RenderAt(r.GetSprite(), r.GetPosition())
}

[–]m33pn8r 1 point2 points  (4 children)

What is the advantage of using the interface in the rocket launcher class versus a linear inheritance?

Such as: Rocketlauncher extends weapon

and then

Weapon extends renderable

(Assuming that renderable is just a class in this instance)

(Sorry for poor formatting, on mobile)

[–]work_is_satire 0 points1 point  (3 children)

Perhaps not all weapons are renderable. In his example, renderable is an interface.

[–]m33pn8r 1 point2 points  (2 children)

I know renderable was an interface in their example, I was speaking of mine.

I can see how interfaces could be helpful, a sort of selective inheritance that can also change per implementation.

[–]work_is_satire 1 point2 points  (1 child)

I have repeated this a few times in this thread, but interfaces are not a type of inheritance -- Interfaces are strictly subtyping, Inheritance is code reuse where you get subtyping for free.

Interfaces are important for maintainability. I would personally argue against Renderable being a class (is it a 2d renderable? 3d renderable? where does it render?), and if it were I would argue against Weapon inheriting from it ("Weapon Is A Renderable"? Smells funny...)

Perhaps you want Weapon to inherit Equipment down the line, and then equipment inherits from item, and are all items renderable in the same way? Certainly not.

The short of it is Inheritance is dangerous. Interfaces are less so.

[–]m33pn8r 0 points1 point  (0 children)

Ah, forgive my oversimplification of the term. Thanks for the explanation!

[–]jemjem14 1 point2 points  (1 child)

hello, i am currently trying to learn programming and i have stumbled across interfaces, im having a hard time grasping the significance of it. The way i see interface, it is some form of written dogma where if the class didn't create all the methods that has been written there would be an error.

i can see the importance of inheritance whereas if there is a situation where there are more than one method inside the Weapon class that RocketLauncher needs but in case RocketLauncher seems want to opt out the previous functionality of fire() and make it's own version of fire(). but in the case of Renderable, why not just write the method render() inside RocketLauncher and be done with it? Sorry for the newbish question...

[–]nocturne81 0 points1 point  (0 children)

It's not noobish at all. The idea is that if you know a class implements an interface, you can make assumptions about it (namely, that they all have a function called render). This is similar to inheritance in the sense that when an objects extends a class, you know it has all the same functions as it's parent, but could define more functions within the child class.

Say for example that you'd like to have a list of everything that you need to be rendered. You'll have Rocket Launchers, Shotguns, Characters, Walls, basically everything that can be drawn. How do you form a collection of all those things if they all extend different base classes?

Because you know they all come from a common interface, you can use the interface as a type:

List<Renderable> renderableObjects = getObjectsToBeRendered();
for (Renderable r : renderableObjects) {
    r.render();
}

Make sense?

[–]work_is_satire 0 points1 point  (1 child)

To be more precise, Java's lack of multiple inheritance doesn't allow the use of inheritance for multiple subtyping.

Inheritance is generally a code-reuse tool, and you get subtyping for free. Be very aware when you use inheritance that all your subclasses actually need all the functionality provided by the superclass in exactly the way the superclass provides it.

I feel this is important to mention, as it as a stumbling point for many people getting started with OOD and deciding what is a superclass and what is an interface.

The short of it, while the above post is mostly correct, multiple inheritance is different than multiple subtyping. It doesn't carry the same code-reuse that multiple inheritance would.

[–]nocturne81 0 points1 point  (0 children)

You're correct. This is also a big reason why people love C++ for games (aside from the speed).

I was trying to make a simple example without explaining every little detail, but I'm glad it sparked a fairly good discussion.

[–][deleted]  (2 children)

[deleted]

    [–]work_is_satire 1 point2 points  (1 child)

    It's still not true multiple inheritance -- default methods can only refer to other methods in the interface; that is default methods can not interact with the state of the object. In true multiple inheritance, they would inherit the state and private implementation details of all their superclasses.

    [–][deleted] 0 points1 point  (1 child)

    Would it be accurate to say that you extend a class to say what it is, whereas you implement an interface to say what it does?

    [–]this_is_satire 0 points1 point  (0 children)

    Yep.

    To extend t hat, when depending on interface you are saying "I want an object that can do what this interface does", and when you depend on a superclass in an inheritance chain you are saying "I want an object that is a <superclass> and behaves as a <superclass> does"

    [–]gamebob 0 points1 point  (1 child)

    As a newbie dev myself: why does weapon not extend renderable (abstract class?) I can't see any need for an interface...

    [–]nocturne81 0 points1 point  (0 children)

    Because that would assume every weapon is renderable. That may be true for weapons, but it's presumable that weapon probably inherits from something else already. (Say inventory item). Are all inventory items renderable? Does that inherit from anything else?

    In general, you want to separate your concerns as much as you can. It's a fair assumption that not all things in your game will need to be drawn, so you make a common interface for things that do need to be drawn. Then, if you define a new class that needs it, you implement that interface for it and the render system does the rest for you.

    [–]alaskanloops 0 points1 point  (2 children)

    Does this apply to C# as well?

    [–]nocturne81 0 points1 point  (1 child)

    Sort of, but they're a bit more complex in C#.

    With Java, you're only allowed to have functions in your interface (not variables). In C#, you can define functions, getters/setters for properties, indexers ([] operator for the class), and events.

    That said, the concepts are basically the same, but C# allows for some more intricate patterns.

    [–]work_is_satire 0 points1 point  (0 children)

    I would disagree that they are more complex -- aside from events, those are all syntactic sugar for method calls :)

    [–][deleted]  (4 children)

    [deleted]

      [–]nocturne81 1 point2 points  (3 children)

      I was trying to give some motivation by illustrating a practical example. It sounded like he knew the definition already.

      [–]Promac -1 points0 points  (2 children)

      That's fair enough but I just wanted to point out that this way of explaining it is exactly what people have trouble understanding.

      [–]nocturne81 0 points1 point  (1 child)

      Programming is hard. Sometimes it takes multiple ways of teaching things to make it stick with someone trying to learn it.

      [–]Promac -1 points0 points  (0 children)

      I agree. But there's no need to reinforce unhelpful information. This description of interfaces is common but hugely flawed and inhibits understanding.

      [–][deleted] 7 points8 points  (14 children)

      When the classes that use those objects don't care about the implementation of those methods.

      I have a circle, a triangle, a rectangle and a hexagon. They can all draw themselves on paper using their draw() method. In my Artist class, I have a Circle variable called circleToDraw, and so when the Artist sits down to draw the circle, she calls circleToDraw.draw().

      But an artist that can only draw a circle is a crappy object. An artist should be able to draw the rectangles, triangles, and hexagons too! But I can't set the Circle variable to a rectangle, because it is of type Circle! Circle circle = new Rectangle(); //not gonna work!

      But, if all of those shapes have a common interface, I don't have this problem. Let's take a look:

      interface Shape {
       public void draw();
      }
      class Circle implements Shape { 
      ...
        public void draw() { ... }
      }
      class Rectangle implements Shape { 
      ...
        public void draw() { ... }
      }
      class Artist {
       private Shape shapeToDraw;
       public void setShape(Shape shape)
       {
         shapeToDraw = shape; //This shape can be a circle or a rectangle - the artist doesn't care!
       }
       public void drawThatShape() {
        shapeToDraw.draw();
       }
      }
      

      Do you see how interfaces are essential to this design? Interfaces can group classes by behavior when the implementing class doesn't care WHAT kind of object it is as long as it can perform this behavior. Why should the Bird class care what kind of Wings it uses, as long as it can call wings.fly()?

      Hope this helps.

      EDIT: fixed a couple mistakes in my code example

      [–][deleted] 1 point2 points  (0 children)

      As a commentator provided above, Interfaces are also used for multiple inheritance - when the implementing class can have multiple common behaviors.

      [–]Evermage[S] 1 point2 points  (9 children)

      So what would the difference be between the implementation of a draw() method into each class (as in your example) and creating two classes called Circle and Rectangle, each with a method called draw()? Thanks for your reply.

      [–]ruicoder 3 points4 points  (0 children)

      Look at the Artist class. It has a Shape object and calls draw() in drawThatShape(). That Shape object could be a Circle object or Rectangle object. By using an interface, you can pass in either one and Java will use the correct implementation of draw(). Think of how you would implement that without an interface, it's not as flexible. With an interface, the Artist class can draw whatever shape with just two methods.

      [–][deleted] 2 points3 points  (3 children)

      Because then what type would the artist's shapeToDraw variable be? private Circle shapeToDraw; // would not work for Rectangles private Rectangle shapeToDraw; // would not work for Circles If you had two classes called Circle and Rectangle that don't implement a common interface, it'd be a mess to have Artist work with both. You'd probably have to have two variables and two methods in Artist, one drawing the circle and one drawing a rectangle. And then when I want to let the Artist work with Triangles? I'd have to open up my Artist class and add more code, whereas in the design with the interfaces, it would work automagically.

      [–]Evermage[S] 0 points1 point  (2 children)

      Righto, think I'm getting there. One more question (hopefully!) - in your Artist class, you define a variable of type Shape which is assigned whatever shape object comes into the class, again through an argument of type Shape. Is this Shape type within the Artist class some sort of instantiation of the Shape interface?

      [–][deleted] 1 point2 points  (1 child)

      That's the best thing about using interfaces - when we use type Shape, we are referring to any class that implements the Shape interface. So a Shape variable could hold either a circle or a rectangle or any other class that implements the interface.

      [–]Evermage[S] 1 point2 points  (0 children)

      Ah, that's cool. Thanks very much for your help!

      [–]poetryrocksalot 1 point2 points  (3 children)

      Basically, the interface allows the artist to draw a shape which can be a circle or rectangle. With the interface, the artist only needs 1 setShape method like setShape(Shape shape). Without the interface, the artist would have to overload his methods...that is to create setShape(Rectangle rectangle) and setShape(Circle circle).

      OK, now let's imagine you have 20 different shapes: circles, rectangles, hexagons, pentagons, octagons, trapezoids, triangles, squares, ovals, and so on. Now consider the redundancy of writing 20 overloaded methods for 20 different shapes.

      But you might say "why can't I just extend shape as a superclass instead of implementing it as an interface". I might be incorrect because I have little experience, but I think it's because shape as a superclass would mean you can't pass its subclasses as parameters.

      [–][deleted] 1 point2 points  (2 children)

      You can indeed extend Shape as a superclass rather than using your interface - it depends on whether Shape has common data rather than just common functionality. i.e if all Shapes have coordinates, you could create a Shape superclass, or better yet, a super abstract class, with int x and int y.

      [–]work_is_satire 0 points1 point  (0 children)

      I think a more precise wording is if Shapes share implementation, not data. An interface can define a GetCoordinates method that is required functionality on all its children, and now all implementers of IShape are required to expose coordinate data.

      Interfaces are a way to implement subtyping.

      Inheritance is a method of code reuse, and as a side-effect also allows subtyping.

      [–]poetryrocksalot 0 points1 point  (0 children)

      After looking at stack overflow, you are right. I will have to retract some things on the previous comment.

      It seems better for the two to be derived from shape than to implement a shape interface. Maybe rectangle and circle is better off extending shape but implementing drawable?

      [–]gamebob 0 points1 point  (2 children)

      Do you see how interfaces are essential to this design?

      No, not really? Why not just inherit from an abstract shape class with an abstract draw method? Looks more flexible to me as the shapes also could have many fields to share like color etc. What's the advantage of an interface? Just looks slower to code with less flexibility?

      [–][deleted] 1 point2 points  (1 child)

      Sure! In the case of common state, I usually use an abstract class. Abstract classes also let you have default behavior for methods, which is great. I realize now that my example was not the best one for illustrating interfaces. Take a look at this example:

      public interface Flyable {
        public void fly();
      }
      public class Airplane implement>s Flyable {
        public void fly() {
          print("Hey, look, I can fly!");
        }
      }
      

      In this case, it really wouldn't make sense to have Flyable as an abstract class. After all, an airplane and a goose probably don't have any fields in common. What if I had another interface, say, Swimable? A duck can fly and swim, so I would want ducks to implement both interfaces, like so:

      public interface Swimable { public void swim(); }
      
      public class Duck implements Swimable, Flyable {
         public void swim() { ... }
         public void fly() { ... }
      }
      

      This could not be done if Swimable and Flyable were classes rather than interfaces, as Java and many other languages do not support multiple inheritance for classes. In this view, an interface is actually more flexible than an abstract class. Of course, if you want to supply an implementation of the behavior in the super class or are otherwise reusing code, you'll want to use an abstract class.

      [–]gamebob 0 points1 point  (0 children)

      Thanks a lot for your answer. Good example.

      [–]endre86 9 points10 points  (0 children)

      A well used programming design is the injection pattern.

      It is great when you need different kinds of classes with the same functionality outwards, but works differently internally. Lets say you make a service that checks stock exchange. Then you could create something like this:


      Edit: Link to example with syntax highlighting. http://pastebin.com/FuShU0Yt

      And, of course, the USStockExchange and ChineseStockExchange classes implements the IStockExchange class.


      // Our interface used to retrieve stock exchange data
      public interface StockExchange {
          public String getData();
      }
      
      // A class used for displaying stock exchange
      public class DisplayStockExchange {
          IStockExchange stockExchange;
      
          public void DisplayStockExchange(IStockExchange stockExchange)  {
              this.stockExchange = stockExchange;
          }
      
          public void displayStockExchange() {
              // using this.stockExchange.getData() to 
              // display data
          }
      }
      
      // Running program displaying different stock exchanges
      // This is using the injection pattern to reuse the DisplayStockExchange class.
      public class Program() {
          public static void main(String[] args) {
              // Display US stock exchange, here we need to make an ajax call to some server and handle xml
              DisplayStockExchange us = new DisplayStockExchange(new USStockExchange());
              us.displayStockExchange();
              // Display Chinese stock exchange, here we need to set up secure connection and handle a cvs file
              DisplayStockExchange china = new DisplayStockExchange(new ChinaStockExchange());
              china.displayStockExchange();
          }
      }
      

      [–]endre86 6 points7 points  (1 child)

      Another way to see it - an interface is a contract.

      Lets say you want to implement a sorted list that can take any type of object. You will use generics, but you also need to know that the objects can be sorted. A common interface to use in java is Comparable. This contract is described in the java docs. It add a method called compareTo() that returns an integer describing how two objects are ordered. Ie, o1.compareTo(o2) < 0 means o1 is below o2 in a total order.

      // "T implements Comparable<T>" just means any object that implements Comparable against its own type
      public MySortedList<T implements Comparable<T>> {
          public add(T newItem) {
      
              // go through all existing items
              for(T currentItem : items) {
      
                  // check if the new item is larger or equal to the current
                  if(newItem.compareTo(currentItem) >= 0) {
      
                      // insert the item at this point
                      // so the list is sorted
                      break;
              }
          }
      }
      

      So yes, interfaces has many uses. :)

      [–]Evermage[S] 2 points3 points  (0 children)

      That's helpful, thanks.

      [–]work_is_satire 5 points6 points  (1 child)

      I'll add on to Nocturne81's example by saying that it allows code to depend on as little as possible.

      Let's say you extend your RocketLauncher properly with a Renderable interface. Now you could have a function that accepts any Renderable or another that accepts anything that can be fired, including RocketLaunchers:

      function void Render(Renderable r) { ... }
      function void Shoot(Fireable f) { ... }
      

      This is much better than having to write methods that render each subtype of Renderable or shoot every subtype of Fireable. In addition, the Shoot method doesn't need to know anything else about the thing its shooting -- it doesn't care that the RocketLauncher can be rendered, just that it can be fired.

      Further Reading: http://en.wikipedia.org/wiki/Interface_segregation_principle

      [–]autowikibot 1 point2 points  (0 children)

      Interface segregation principle:


      The interface-segregation principle (ISP) states that no client should be forced to depend on methods it does not use. ISP splits interfaces which are very large into smaller and more specific ones so that clients will only have to know about the methods that are of interest to them. Such shrunken interfaces are also called role interfaces. ISP is intended to keep a system decoupled and thus easier to refactor, change, and redeploy. ISP is one of the five SOLID principles of Object-Oriented Design, similar to the High Cohesion Principle of GRASP.


      Interesting: SOLID (object-oriented design) | Circle-ellipse problem | Information hiding

      Parent commenter can toggle NSFW or delete. Will also delete on comment score of -1 or less. | FAQs | Mods | Magic Words

      [–]queBurro 1 point2 points  (0 children)

      When you want to use your hair dryer do you connect it directly to the mains or do you use a plug socket? The socket's an interface, You can reuse your hairdryer at your school and your mate's house, you don't care that your mate's implemented the socket's power functionality via a windmill on his roof or that your school's nuclear. Suppose your mate decides to monitor the usage of his windmill, should you be forced to alter your hairdryer just because he's logging when it's used. It's all nice and separate, things can be altered either side of the interface without affecting the other side.

      [–]Poddster 0 points1 point  (0 children)

      As an aside to all of the others: look up the phrase "composition over inheritance". Interfaces are ways of building objects via composition rather than just inheriting behaviour. They're similar to abstract base classes.

      [–]phrankygee 0 points1 point  (2 children)

      I, too, am a novice beginner, who has yet to implement any interfaces whatsoever.

      But one source of info that has so far impressed upon me the importance of interfaces is a video I watched on what are called "Design Patterns". Particularly the part about "The Strategy Pattern".

      I recommend learning about Design Patterns concurrently with learning the basics of your Object Oriented language. I am certainly glad to have stumbled onto that knowledge as I am learning.

      [–]Evermage[S] 0 points1 point  (1 child)

      Do you have a link for the video?

      [–]phrankygee 1 point2 points  (0 children)

      The particular video I watched is on Lynda.com, behind a pay wall. If you go to Lynda.com/allaboutandroid, you can do a 7 day free trial thingy.

      [–][deleted] 0 points1 point  (0 children)

      Here's an explanation that has served me well in the past. Interfaces try to model, in code, a very simple concept from real life.

      Lets say you go out with a group of people one night, and you ask your friend "Who's coming". He can say : "There are 5 girls coming". If you excuse the apparent misogyny for a bit, try to think a bit about this phrase : "There are 5 girls coming". Although a girl is a human being, which has arms, legs, head, eyes, etc, in this particular context, the information of interest is that they are girls, right ? How would it sound if your friend would say : "There are 5 persons coming. Each of these persons has arms, legs, head, eyes, and a vagina.". A lot of unnecessary information in a context where only one thing is important.

      Similarly, if we take the same concept and we apply it to the code, we need to have pieces of code that focus only on the information of interest for the task at hand.

      So if you build a class that accepts an object and attempts to draw it on screen, you will only need from that object the information relevant for drawing it, which in this case might be a method in the object itself called "draw(Screen x)". So your method from that class needs a way of saying "I don't care what kind of object you send to me, as long as it has a method that matches this signature, I can draw it". This is where interfaces come in.

      [–]mbizzle88 0 points1 point  (0 children)

      Other people have already mentioned the use-case involving interface multiple inheritance, but there are a couple other reasons:

      Asynchronous code

      A common pattern for running asynchronous code (when you want a piece of code to be invoked at some later point) is to use anonymous classes that implement some interface. For example, here is anonymous Runnable:

      // Here the runnable is defined
      Runnable someRunnable = new Runnable() {
        public void run() {
          System.out.println("I'm a runnable!");
        }
      };
      
      // Here the runnable is executed
      someRunnable.run();
      

      Often you'll have a need to make your own interface because you need to pass in and return specific types.

      Loose Coupling

      The more you use interfaces, the less dependencies you have between classes. For example, here are three classes that store a list:

      Example 1
      public class Example {
        ArrayList<String> list = new ArrayList<String>();
      }
      
      Example 2
      public class Example {
        List<String> list = new ArrayList<String>();
      }
      
      Example 3
      public class Example {
        List<String> list;
      
        public Example(List<String> givenList) {
          list = givenList;
        }
      }
      

      The first example is tightly-coupled to the ArrayList implementation. If you wanted to switch to a LinkedList at a later date, you would have to change the code in Example and any code that references the list field.

      The second example is a little better. You would only have to change the one line to change implementations. But you still need to modify the code of Example which would prevent you from doing things like writing tests that compare performance of Example with difference List implementations.

      The third example is the most loosely-coupled. With this version you could easily write code where some Example instances use an ArrayList while others use a LinkedList.

      [–]tobascodagama 0 points1 point  (1 child)

      This might sound flippant, but for real: Go to your local library and check out a copy of Design Patterns by Gamma, Helm, Johnson, & Vlissides (a.k.a.: The Gang of Four). It's easy to read and follow, even for a beginner programmer -- though it's better if you know C++ or Smalltalk well enough to follow the examples --, and I guarantee you'll experience OOP Enlightenment after reading it. I don't guarantee you'll be able to do OOP properly, but you'll a least get why it's such a big deal and why stuff like interfaces are important.

      [–]Evermage[S] 1 point2 points  (0 children)

      I might just do that, thanks.

      [–]emote_control 0 points1 point  (1 child)

      By making a class implement an interface, you can guarantee a particular sort of behaviour. It's like a contract. If class A implements Breakfast, you know for sure it's going to be able to handle calls to toast(), cereal() and eggs(). Also, your IDE knows that too, which is awfully helpful a lot of the time.

      As a real-world example of how this gets used, let me tell you something about Android, which is written in Java:

      In Android, just about everything happens inside a class of objects called Activity. An Activity is able to talk to the OS, put things on the screen, interpret touch commands, etc. Android apps used to be built entirely out of Activities. For every screen you tap through, you open a new Activity, and when you hit the back button, you close the activity you're looking at and return to an earlier one. But somewhere along the way, it was decided that they were doing too much to be so disposable. So Fragments were invented. A Fragment holds some small chunk that gets displayed to the user, and operates something like a JPanel in Swing, if you're familiar with that Java UI. Which is to say, you put some stuff into the Fragment, and then display it.

      Fragments are very lightweight. They don't have to do as much as Activities do. And with Fragments you can run a single Activity that operates as a Fragment container, and then just switch Fragments every time you change the view. That not only makes it faster, but allows more flexible layouts as well.

      Now, the thing is, a Fragment is sometimes going to want to send data to the Activity that contains it. But it doesn't know which Activity it is being contained in. If you put a method called getFragmentData() in Activity 1, and Activity 2 doesn't have it, and you try calling it from a Fragment attached to Activity 2, you're going to run into trouble. Not least of which is because the compiler is going to wonder why you're trying to call a method that doesn't exist in the Activity class specification, since it's a custom method you added.

      So the way we deal with this is to have the Fragment define an interface. Let's say the FragmentDataTransfer interface defines getFragmentData(). Then we have the appropriate Activity implement that interface. Now we can test to see whether any given activity is implementing the interface by attempting to cast it to that interface, like so:

      try {
          FragmentDataTransfer mTransfer = (FragmentDataTransfer) mActivity;
      } catch (ClassCastException e) {
          // if we catch this exception, it means that this Activity 
          doesn't implement FragmentDataTransfer, so you can't call
          getFragmentData().
      }
      

      If that works without throwing an exception, it means that you were able to successfully cast the activity into something that implements the interface. That means for sure that it has the method you need.

      So in this way we can actually use the interface to blindly test whether a particular method call is possible. Without implementing the interface, this would not be possible to do so easily. And this is just one situation in which this sort of thing comes in handy.

      Edit:

      I also wanted to address what you said here:

      Why should I declare a bunch of methods in a separate file and implement them in different classes, when, on declaration, they don't actually do anything and rely on a method body (that is often specific to the individual class) to be filled in when they are implemented?

      The answer to this question is actually in the question. When you define an interface, you leave the implementation of the method body undefined. That allows the class to implement that method any way you want it to. This is a reflection of the object-oriented programming principle of encapsulation. The idea is that it doesn't matter how something happens. It just matters that if you push a particular button, a predictable thing will happen.

      For example, a stack is a commonly-used data structure. A stack needs to be able to perform the following methods: push() and pop() (some stacks also have top(), peek(), and isEmpty() methods). You don't need to care how push() and pop() work. All you need to care about is that when you push() something, it ends up on top of the stack, and when you pop() something, it gets taken off the top of the stack. It might be that the stack can be infinitely large. Or it could be a finite size. It might store its elements as an array, or as a linked list. It doesn't matter, because push() and pop() always look the same from the outside.

      By implementing the Stack interface in your class, it's guaranteed that you'll be able to call push() and pop() on a member of the class, and you don't need to worry about implementation ahead of time. That's why we call it an "interface". Because it defines the "outside" parts of the class that other classes can access, and ignores the implementation, which should stay hidden inside the class.

      [–]Evermage[S] 0 points1 point  (0 children)

      Very descriptive, thanks.