C# abstract抽象类的作用(使用场景)

对于C#初学者来说,abstract抽象类在网上的定义和解释说了一大堆,却往往我们忽视了为何要使用abstract类,使用它的意义在哪里。面试的时候也会有人问起使用它有什么好处,因为不适用它用自己定义的类也可以实现。那么为什么要使用抽象类?

那么我们什么时候应该用抽象类呢?
如果一个类设计的目点是用来被其它类继承的,它代表一类对象的所具有的公共属性或方法,那个这个类就应该设置为抽象类。

抽象类与其它的类有什么区别呢?
抽象类是不能够被实例化的。如果一个类中包含有抽象方法,那么这个类一定要声明为抽象类。同时,抽象方法一定需要在子类中重写,让抽象方法成为一个具体的实实在在的方法。

相信大家在网上一定看过很多这类解释了吧?好吧,不理解的我们一起来看看通俗易理解的说法吧:

比如说:我们需要创建 “狗”、“猫”、“鱼”、“马”这些对象(类),我们可以说他们有一些共同的属性像嘴巴、尾巴、重量、颜色、大小等等一些共同的属性(properties),但是它们彼此的属性的形状是不同的(如嘴巴),在这种情况下,我们如果一个个去定义各自类似的属性是不是比较繁琐?如果用抽象类是不是很方便的给他们去继承。抽象类也有个更加好的地方,体现在“同质异像”就是实质相同实现形式不同的方法继承上,例如上面的狗、猫、马等的呼吸这个方法或者跑的速度的方法形式不同,我们这个是用定义一个抽象方法,让他们各自的类去实现它是不是很方便。“抽象”的意义正在于此。将共同的东西抽出来封装,但不实现只给继承。

现在懂了吧???

英语厉害的同学也可以看看英文的通俗说法:

Abstract classes are useful when you need a class for the purpose of inheritance and polymorphism, but it makes no sense to instantiate the class itself, only its subclasses. They are commonly used when you want to define a template for a group of subclasses that share some common implementation code, but you also want to guarantee that the objects of the superclass cannot be created.

For instance, let's say you need to create Dog, Cat, Hamster and Fish objects. They possess similar properties like color, size, and number of legs as well as behavior so you create an Animal superclass. However, what color is an Animal? How many legs does an Animal object have? In this case, it doesn't make much sense to instantiate an object of type Animal but rather only its subclasses.

Abstract classes also have the added benefit in polymorphism–allowing you to use the (abstract) superclass's type as a method argument or a return type. If for example you had a PetOwner class with a train() method you can define it as taking in an object of type Animal e.g. train(Animal a) as opposed to creating a method for every subtype of Animal.

(selected from:http://stackoverflow.com/questions/2570814/when-to-use-abstract-classes

如果对你学习理解有帮助,可以顶一下哈!有什么讲错的欢迎指点批评,你我学习共同进步!!!




原文地址:https://www.cnblogs.com/zorrobubble/p/3596905.html