what is the advantage of interface over abstract c

2020-05-19 04:16发布

Abstract class have both concrete and abstract function . interface only have abstract functions.

Overriding is possible in both. Is it

What is the real time advantage of one over the other ?

标签: java oop
9条回答
家丑人穷心不美
2楼-- · 2020-05-19 04:34
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.

查看更多
时光不老,我们不散
3楼-- · 2020-05-19 04:37

Interfaces are useful because Java doesn't have multiple inheritance (but you can implement as many interfaces as you like).

Abstract classes are useful when you need concrete behaviour from the base class.

查看更多
Rolldiameter
4楼-- · 2020-05-19 04:43

You dont override an interface. You implement it.

Writing an interface gives implementors the ability to implement your interface and also other interfaces in addition to inheriting from a base class.

Abstract classes can be partially or fully implemented.Marking a class abstract just prevents you from instantiating an object of that type.

查看更多
登录 后发表回答