Is there more to an interface than having the correct methods

后端 未结 17 666
小鲜肉
小鲜肉 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 { }
    
    0 讨论(0)
  • 2020-11-22 14:34

    you could do

    Ibox myBox = new Rectangle();
    

    that way you are using this object as Ibox and you don't care that its really Rectangle .

    0 讨论(0)
  • 2020-11-22 14:34

    A great example of how interfaces are used is in the Collections framework. If you write a function that takes a List, then it doesn't matter if the user passes in a Vector or an ArrayList or a HashList or whatever. And you can pass that List to any function requiring a Collection or Iterable interface too.

    This makes functions like Collections.sort(List list) possible, regardless of how the List is implemented.

    0 讨论(0)
  • 2020-11-22 14:35

    The purpose of interfaces is abstraction, or decoupling from implementation.

    If you introduce an abstraction in your program, you don't care about the possible implementations. You are interested in what it can do and not how, and you use an interface to express this in Java.

    0 讨论(0)
  • 2020-11-22 14:37

    If you have CardboardBox and HtmlBox (both of which implement IBox), you can pass both of them to any method that accepts a IBox. Even though they are both very different and not completely interchangable, methods that don't care about "open" or "resize" can still use your classes (perhaps because they care about how many pixels are needed to display something on a screen).

    0 讨论(0)
提交回复
热议问题