interface vs abstract class [duplicate]

ぃ、小莉子 提交于 2019-12-08 09:50:48

问题


Possible Duplicate:
Interface or abstract class?

I have a group of classes defined as follows:

namespace VGADevices.UsingAbstractClass
{
    public abstract class VGA
    {
        public abstract int HorizontalResolution { get; set; }
        public abstract int VerticalResolution { get; set; }
    }
    public class LCDScreen : VGA
    {
        public override int HorizontalResolution { get; set; }
        public override int VerticalResolution { get; set; }
    }
}  // namespace VGADevices.UsingAbstractClass

namespace VGADevices.UsingInterfaces
{
    public interface IVGA
    {
        int HorizontalResolution { get; set; }
        int VerticalResolution { get; set; }
    }
    public class LCDScreen : IVGA
    {
        public virtual int HorizontalResolution { get; set; }
        public virtual int VerticalResolution { get; set; }
    }
}  // namespace VGADevices.UsingInterfaces

Client code, I have the choice between:

class Computer
{
        public VGA VGAOutput { get; set; }
}

or

class Computer
{
        public IVGA VGAOutput { get; set; }
}

I read somewhere that using interfaces is better, but why? With abstract classes I can define an interface as well plus add data-members so why are interfaces the preferred method? Does binary replacement play a role here as well?

thank you

Chris


回答1:


You can inherit from(that is, implement) multiple interfaces. You can't inherit from multiple abstract classes




回答2:


Check out this post:

http://www.codeproject.com/KB/cs/abstractsvsinterfaces.aspx

Most important features I see: Multiple inheritance (interface can implement multiple interfaces, abstract can inherit from only one) Homogeneity (I have two objects with the same interface, but they're really not they same object and shouldn't share any code)



来源:https://stackoverflow.com/questions/6446723/interface-vs-abstract-class

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