我什么时候应该在界面上选择一个抽象类? [英] When should I choose an abstract class over an interface?

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

问题描述

我已经对这个答案进行了大量的搜索,我得出了下面提到的结论。



我想知道它是否足够选择其中一个的理由是什么?



我尝试过:



当我们有一些默认的功能或方法时,使用抽象类,其定义对于所有子类来说都是相同的。因此,通过使用抽象类,我们不必一次又一次地编写相同的代码,即使将来如果我们需要更改我们只需要在一个地方进行更改所需的功能。

I have done lots of search regarding this answer and I've come up with conclusion mentioned below.

I want to know whether it is a fairly enough and a justified reason for choosing one over the other?

What I have tried:

Use abstract class when we have some default functionality or methods whose definition will remain same for all
the sub-classes. So by using abstract class, we do not have to write same code again and again, even in future if
we need to change the functionality we just need to make changes at a single place.

推荐答案

请抄写: oop - 接口与抽象类(通用OO) [ ^ ]


最简单的答案是,当我们有一些默认行为对于每个从基类型继承的派生类都是相同的那么抽象类是合适的,因为我们可以定义具有实现的方法,也将由子类重用。虽然对于接口我们只定义了签名,这意味着它只能说明在某些类型实现时它希望提供什么样的行为。



注意在较新的在C# 的版本中,我们也可以在接口中定义具有默认实现的方法。



您还可以参考以下主题以获得更清晰:



抽象类与接口



接口与抽象类
The simplest answer is that when we have some default behaviors that will be same for every derived class which would be inheriting from the base type then abstract class is suitable as we can define method with implementation that will be re-used by child classes too. While for interface we only define the signatures which means that it only tell what kind of behaviors it expects to be provided when some type is implementing it.

Note that in newer version of C# we would be able to define methods with default implementation in interfaces too.

You can also refer to the following threads for more clarity:

Abstract Class versus Interface

Interfaces vs. abstract classes


这篇关于我什么时候应该在界面上选择一个抽象类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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