使用抽象类与常规类的好处 [英] Benefits of using an abstract classes vs. regular class

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

问题描述

我决定自己开始做一些专注于代码质量而不是代码数量的小型编码项目,并且对抽象类的使用有疑问.

I have decided to start doing small coding projects on my own that focus on code quality instead of code quantity and have a question about the use of abstract classes.

现在我知道抽象类和接口之间的区别,最大的区别(我认为)是接口允许您只定义需要由使用接口的类实现的方法,而抽象类允许您定义方法和如果您愿意,成员以及默认方法实现.我的问题是使用抽象类与普通类的主要好处是什么?我能想到的两者之间唯一真正的区别是您不能创建抽象类的实例.两者之间还有其他区别吗?

Now I know the differences between abstract classes and interfaces with the biggest one (I think) being that interface allow you to only define methods that need to be implemented by classes using the interface and abstract classes allowing you to define both method and members along with default method implementation if you so desire. My question is what the the main benefit of use an abstract class vs a normal class? The only real difference between the two that I can think of is that you can not create an instance of an abstract class. Are there any other differences between the two?

推荐答案

严格来说,从设计的角度来看,最好是简化事情.我相信简化事情的最好方法是使用一个简单的类比.让我们用鸟类来比喻...

Strictly from a design perspective, it is best to simplify things. I believe the best way to simplify things is to use a simple analogy. Let's use an analogy of birds...

接口:当您想强制执行某些需要定义的功能时使用此接口.例如IBird 有 ScreamLikeABird 和 Fly(接口函数)的合同.但是您可以得到更具体的信息,并拥有一个具有运行合同的 IOstrich.你可能还有一个 IHawk,它有一个 Attack 合约......等等.

Interface: use this when you want to enforce certain functions which need to be defined. e.g. IBird has a contract for ScreamLikeABird and Fly (interface functions). But you can get more specific and have an IOstrich that has a Run contract. You may also have an IHawk that has an Attack contract...etc.

摘要:当您想要强制执行基本函数并具有基本属性时使用此选项.例如Avian 可能是鸟类的基类,它可能具有名为 LayEgg 的函数以及名为 Age、Species、NumberOfChicks 等的属性.这些东西不会/不应该改变鸟类的行为,因为所有的鸟类都会产卵……等等.但并不是所有的鸟在以相同的方式尖叫或飞行时听起来都一样(有些甚至不会飞......等等......因此它们应该通过接口实现).

Abstract: use this when you want to enforce base functions and have base properties. e.g. Avian could be a base class for birds which may have a function called LayEgg as well as propeties called Age, Species, NumberOfChicks...etc. These things don't/shouldn't change the behavior of a bird, since all birds lay eggs...etc. But not all birds sounds the same when it scream or flies the same way (some dont even fly)....etc.... hence they should be implemented via an interface(s).

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

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