what is the advantage of interface over abstract classes?

前端 未结 9 1884
野的像风
野的像风 2021-02-01 05:48

In Java, abstract classes give the ability to define both concrete and abstract methods whereas interfaces only give the ability to implement abstract methods. I believe overrid

相关标签:
9条回答
  • 2021-02-01 06:37

    Interfaces are for when you want to say "I don't care how you do it, but here's what you need to get done."

    Abstract classes are for when you want to say "I know what you should do, and I know how you should do it in some/many of the cases."

    Abstract classes have some serious drawbacks. For example:

    class House {
    
    }
    
    class Boat {
    
    }
    
    class HouseBoat extends /* Uh oh!! */ {
        // don't get me started on Farmer's Insurance "Autoboathome" which is also a helicopter
    }
    

    You can get through via an interface:

    interface Liveable {
    
    }
    
    interface Floatable {
    
    }
    
    class HouseBoat implements Liveable, Floatable {
    
    }
    

    Now, abstract classes are also very useful. For example, consider the AbstractCollection class. It defines the default behavior for very common methods to all Collections, like isEmpty() and contains(Object). You can override these behaviors if you want to, but... is the behavior for determining if a collection is empty really likely to change? Typically it's going to be size == 0. (But it can make a big difference! Sometimes size is expensive to calculate, but determining whether something is empty or not is as easy as looking at the first element.)

    And since it won't change often, is it really worth the developer's time to implement that method every... single... time... for every method in that "solved" category? Not to mention when you need to make a change to it, you're going to have code duplication and missed bugs if you had to re-implement it everywhere.

    0 讨论(0)
  • 2021-02-01 06:37
    class Animal
    { void move(){} }
    
    class Bird
    { void move(){fly} }
    
    class Fish
    { void move(){swim} }
    

    Now, if class Animal is abstract class like

    Animal a; 
    
    a= new Bird(); or a = new Fish()
    

    Here, abstraction works well, but if there are 100 objects like Animal a[100];

    You can not write new Bird().move or new Fish().move 100 times

    Use interface and write a[i].move. It will differentiate as bird or fish and that move() will be invoked

    Second it supports multiple inheritance as class A can implements as many interfaces.

    0 讨论(0)
  • 2021-02-01 06:41

    The main advantages of interface over abstract class is to overcome the occurrence of diamond problem and achieve multiple inheritance. In java there is no solution provided for diamond problem using classes.For this reason multiple inheritance is block using classes in java. So to achieve multiple inheritance we use interface .

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