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?