Click Upvote Click Upvote - 1 year ago 124
Java Question

Is there more to an interface than having the correct methods

So lets say I have this interface:

public interface IBox
public void setSize(int size);
public int getSize();
public int getArea();
//...and so on

And I have a class that implements it:

public class Rectangle implements IBox
private int size;
//Methods here

If I wanted to use the interface IBox, i can't actually create an instance of it, in the way:

public static void main(String args[])
Ibox myBox=new Ibox();

right? So I'd actually have to do this:

public static void main(String args[])
Rectangle myBox=new Rectangle();

If that's true, then the only purpose of interfaces is to make sure that the class which implements an interface has got the correct methods in it as described by an interface? Or is there any other use of interfaces?

Answer Source

Interfaces are a way to make your code more flexible. What you do is this:

Ibox myBox=new Rectangle();

Then, later, if you decide you want to use a different kind of box (maybe there's another library, with a better kind of box), you switch your code to:

Ibox myBox=new OtherKindOfBox();

Once you get used to it, you'll find it's a great (actually essential) way to work.

Another reason is, for example, if you want to create a list of boxes and perform some operation on each one, but you want the list to contain different kinds of boxes. On each box you could do:


(assuming IBox has a close() method) even though the actual class of myBox changes depending on which box you're at in the iteration.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download