什么时候使用抽象类?

编程入门 行业动态 更新时间:2024-10-14 22:18:19
本文介绍了什么时候使用抽象类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

更多推荐

什么时候使用抽象类?

本文发布于:2023-11-07 00:02:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1565015.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:什么时候   抽象类

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!