何时使用抽象类? [英] When to use abstract classes?

查看:181
本文介绍了何时使用抽象类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是抽象类的MSDN文章,但我真的不明白这一点......

Here is the MSDN article on abstract classes, but I really don't get it...

当我应该真正使用抽象类?什么是使用抽象类的优势是什么?

When should I really use abstract classes? What are the advantages of using abstract classes?

推荐答案

当你需要一个类继承和多态的目的,抽象类是有用的,但它是没有意义的实例化类本身,只有它的子类。当你要定义为一组子类具有某些共同实施code的模板,它们通常使用,但是你也想确保不能创建超类的对象。

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.

例如,假设您需要创建狗,猫,仓鼠和鱼类的对象。他们拥有一样的颜色,大小,和腿部的一些相似的性质,以及行为,以便创建一个Animal超。然而,是什么颜色的动物是什么?多少条腿没有一个动物的对象有哪些?在这种情况下,它并没有多大意义,实例化Animal类型的对象,而是只有它的子类。

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.

抽象类也有多态性,让您在使用的(抽象)超类的类型作为方法的参数或返回类型的好处。例如,如果你有一个PetOwner类与列车()方法,你可以将其定义为接受型的动物如的对象火车(动物),而不是创造动物的每一个亚型的方法。

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.

这篇关于何时使用抽象类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆