Default Interface Implementations. What is deep meaningful difference now, between abstract class and interface?

跟風遠走 提交于 2019-11-30 09:17:35

There is not a lot of difference between the two apart from the obvious fact that abstract classes can have state and interfaces cannot. Default methods or also known as virtual extension methods have actually been available in Java for a while. The main drive for default methods is interface evolution which means being able to add methods to an interface in future versions without breaking source or binary compatibility with existing implementations of that interface.

another couple of good points mentioned by this post:

Another thing which still makes the interface unique is covariance / contravariance.

To be honest, never found myself in situation where a default impl. in interface was the solution. I am a bit sceptical about it.

The only main difference coming to my mind is that you can still overload the default constructor for abstract classes which interfaces will never have.

abstract class LivingEntity
{
    public int Health
    {
        get;
        protected set;
    }


    protected LivingEntity(int health)
    {
        this.Health = health;
    }
}

class Person : LivingEntity
{
    public Person() : base(100)
    { }
}

class Dog : LivingEntity
{
    public Dog() : base(50)
    { }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!