Is there more to an interface than having the correct methods

后端 未结 17 896
小鲜肉
小鲜肉 2020-11-22 13:37

So lets say I have this interface:

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


        
17条回答
  •  感情败类
    2020-11-22 14:17

    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:

    myBox.close()
    

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

提交回复
热议问题