什么时候使用抽象类? [英] When to use abstract classes?

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

问题描述

这是关于抽象类的 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?

推荐答案

当您需要一个类来实现继承和多态时,抽象类很有用,但是实例化类本身没有意义,只实例化它的子类.它们通常用于为一组共享一些公共实现代码的子类定义模板,但又要保证无法创建超类的对象.

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.

例如,假设您需要创建 Dog、Cat、Hamster 和 Fish 对象.它们具有类似的属性,如颜色、大小和腿数以及行为,因此您可以创建一个 Animal 超类.然而,什么颜色是动物?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.

抽象类还具有多态性的额外好处——允许您使用(抽象)超类的类型作为方法参数或返回类型.例如,如果您有一个带有 train() 方法的 PetOwner 类,您可以将其定义为接收一个 Animal 类型的对象,例如train(Animal a) 而不是为每个 Animal 子类型创建一个方法.

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天全站免登陆