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

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

问题描述

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

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(接口功能)签有合同.但是,您可以获得更多具体信息,并拥有拥有Run合同的IOstrich.您可能还会有一个具有攻击合同的IHawk ...等.

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.

摘要:当您要强制执行基本功能并具有基本属性时,请使用此选项.例如禽类可能是鸟类的基类,可能具有称为LayEgg的功能以及称为年龄,物种,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天全站免登陆