Is there more to an interface than having the correct methods

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

    Normally Interfaces define the interface you should use (as the name says it ;-) ). Sample

    
    public void foo(List l) {
       ... do something
    }
    

    Now your function foo accepts ArrayLists, LinkedLists, ... not only one type.

    The most important thing in Java is that you can implement multiple interfaces but you can only extend ONE class! Sample:

    
    class Test extends Foo implements Comparable, Serializable, Formattable {
    ...
    }
    
    is possible but
    
    class Test extends Foo, Bar, Buz {
    ...
    }
    
    is not!

    Your code above could also be: IBox myBox = new Rectangle();. The important thing is now, that myBox ONLY contains the methods/fields from IBox and not the (possibly existing) other methods from Rectangle.

提交回复
热议问题