2

This question is asked in my effort to understand interface in Java/C#. As my programmer friend told me, interface is one of the easiest concept to understand but very hard to use effectively. Anybody looking to downvote, please consider guiding me in right direction before downvoting (which I don't mind, provided I get the knowledge I seek for).

I understand how the interface works but it's use seems little vague to me.

Consider this:

public interface Drawable {
public void draw(Graphics g);
}


public class Line implements Drawable {
public void draw(Graphics g) {
. . . // do something---presumably, draw a line
}
. . . // other methods and variables
}

Now, to do something with this I still have to do:

Drawable newObject= new line();

I have a Drawable type but I still need to create new object of the class, line. This being said, correct me if I am wrong, I am still creating an object of class, line which means; writing above code is not helping me to save any memory, if the above thing is done for memory optimization ( I know it is related more to abstraction than memory).

My question is: If the class line has the method that is designated on the interface it implements, why can't I just do the following?

public class Line {
    public void draw(Graphics g) {
    . . . // do something---presumably, draw a line
    }
    . . . // other methods and variables
    }


line newObject= new line();

After all, interface does nothing other than creating a base type. My novice understanding would be: the second one will not need the interface at all and reduce the code.

I can take the same approach and say the same thing for the abstract class also because you still have to provide the concrete subclass with overridden methods. My question there would be, why not declare and create the concrete object without the need of abstract class.

I am sure I am missing something here. What makes interface so useful? For me, it is just adding more code when the actual thing is done by the actual class. Can anybody please care to explain?

Jack_of_All_Trades
  • 10,942
  • 18
  • 58
  • 88
  • Have you read the [Java tutorial on interfaces](http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html), the whole "an interface defines a contract" thing? That doesn't seem useful to you? – Joni Sep 26 '13 at 12:48
  • My dear Joni (nice to see your comment). Yes I have, but still the thing evades me. – Jack_of_All_Trades Sep 26 '13 at 12:49
  • possible duplicate of [Interface vs Base class](http://stackoverflow.com/questions/56867/interface-vs-base-class) – Peter Lawrey Sep 26 '13 at 12:50
  • Think of an interface as a real object, something simple like a physical switch. You know people need the switch to turn things on and off, so you give it an on() and off() method, but you don't implement them as you don't know what the switch will be attached to! It may control a light, or an autopilot, or a computer. Your interface specifies the things a developer / user will need to implement. In this case; they need to implement on and off functionality relevant to their needs. Edit: oops similar example below. Also with interfaces you can achieve very low coupling between two classes. – RossC Sep 26 '13 at 13:21
  • "Unlike interfaces, abstract classes can contain fields that are not static and final, and they can contain implemented methods. Such abstract classes are similar to interfaces, except that they provide a partial implementation, leaving it to subclasses to complete the implementation. If an abstract class contains only abstract method declarations, it should be declared as an interface instead." – RossC Sep 26 '13 at 13:27
  • So what governs the rule that we should use Abstract class or Interface? – Miller Sep 26 '13 at 13:32

7 Answers7

8

writing above code is not helping me to save any memory, if the above thing is done for memory optimization

Good programming practice rarely has anything to do with performance. And in this case, you are right.

After all, interface does nothing other than creating a base type. My novice understanding would be: the second one will not need the interface at all and reduce the code.

You are right for your example. Now consider you have other Drawable than just a Line e.g.

canvas.draw(new Line());
canvas.draw(new Square());
canvas.draw(new Circle());

and you want the developers to be able to add their own shapes. You cannot create a draw method for them all. What you want is something like

class Canvas {
    public void draw(Drawable drawable) { /* ... */ }
}

What makes interface so useful?

https://www.google.com/search?q=What+makes+interface+so+useful gets 138 million hits.

It is hard to imagine what I could say which has not been said so many times before. ;)

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
3

An interface is an approach by which several (perhaps radically different) classes can indicate that they have something in common and can be passed to certain methods that don't care about their radical differences in other areas, only that they are similar in others.

An example from my own code;

public interface ToolAffected {

    public void toolUsedOnMe(Tool tool, PickingResult pickingResult,Mob toolUser);
    public void toolUsedOnMe(BlockTool tool, PickingResult pickingResult,Mob toolUser);
    //use polymorphism for more detailed blocks
}

So if I have a particular Tool then I can use it on anything that implements ToolAffected. That could be parts of the enviroment, players, anything. In this case I have ToolAffecteds picked from their graphics (way beyond the scope of this question), but the important point is that all the code that connects the ToolAffected to the graphics, to using the tool upon it doesn't care even slightly what it actually is, only that it has these two methods.

I use it like this

        ToolAffected pickingResult=picker.picked(cam.getLocation(),cam.getDirection());
        target.toolUsedOnMe((BlockTool)inventory.getSelectedTool(), pickingResult, this);
Richard Tingle
  • 16,906
  • 5
  • 52
  • 77
1

In java

Think of Interfaces as a way out of the complexities involved in multiple inheritance(as it is not supported in Java). That plus it can also be used as polymorphic reference.

Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
0

Difference between Abstact Class and Interface

You can visit this link and you will definitely going to understand the difference between that. This is the best site to understand the OOP Concepts and its implementation. Also there are some examples which will help you in future,

Sagar Rawal
  • 1,442
  • 2
  • 12
  • 39
0

i think , you should atleast go through the SOLID principles and esp Program to an interface not implementation

TalentTuner
  • 17,262
  • 5
  • 38
  • 63
0

Let's say you have some geometric shapes like square, circle. They can all have a representation on the paper. Let's say you have a class(artist?) that knows how to draw shapes. What will you do? Write methods for every shape? In fact, you will end up with more code.

Instead, you can have a method like public void draw(Drawable obj) { obj.draw(); } inside your artist class. All you need now is to implement Drawable for your Square, Circle and other Shape classes.

You will probably say : I will add the draw to the Shape class and the Artist will receive a Shape. This is wrong, maybe my example isn't well picked, but let's assume some shapes you cannot draw. So the functionality must go in the Drawable interface.

Silviu Burcea
  • 5,103
  • 1
  • 29
  • 43
0
  1. You can implement more than one Interface. But you can only extend one class.
  2. Its more abstraction. You define what you can do with an object, like Comparable Movable Closable and so on. The Classes dont have to be in the same hierarchy
Peter Lamby
  • 285
  • 2
  • 7