Is there more to an interface than having the correct methods

后端 未结 17 908
小鲜肉
小鲜肉 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:23

    The purpose of interfaces is polymorphism, a.k.a. type substitution. For example, given the following method:

    public void scale(IBox b, int i) {
       b.setSize(b.getSize() * i);
    }
    

    When calling the scale method, you can provide any value that is of a type that implements the IBox interface. In other words, if Rectangle and Square both implement IBox, you can provide either a Rectangle or a Square wherever an IBox is expected.

提交回复
热议问题