Is there more to an interface than having the correct methods

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

    One of the many uses I have read is where its difficult without multiple-inheritance-using-interfaces in Java :

    class Animal
    {
    void walk() { } 
    ....
    .... //other methods and finally
    void chew() { } //concentrate on this
    } 
    

    Now, Imagine a case where:

    class Reptile extends Animal 
    { 
    //reptile specific code here
    } //not a problem here
    

    but,

    class Bird extends Animal
    {
    ...... //other Bird specific code
    } //now Birds cannot chew so this would a problem in the sense Bird classes can also call chew() method which is unwanted
    

    Better design would be:

    class Animal
    {
    void walk() { } 
    ....
    .... //other methods 
    } 
    

    Animal does not have the chew() method and instead is put in an interface as :

    interface Chewable {
    void chew();
    }
    

    and have Reptile class implement this and not Birds (since Birds cannot chew) :

    class Reptile extends Animal implements Chewable { } 
    

    and incase of Birds simply:

    class Bird extends Animal { }
    

提交回复
热议问题