租房找强哥 發表於 2019-5-21 17:24:00

【翻译】在TypeScript中,Extends和Implements一个抽象类有什么不同

<p>我们知道在TypeScript中一个类既可以被implement也可以被extends,有一些C#或java基础的同学可能会对此感到困惑,因为在上述两个面向对象的语言里面只有接口可以被implement,而只有类才能被extends。那我们来解释一下在TypeScript中这两个关键词有什么不同。最近在StackOverflow中查到了这个问题,所以顺手翻译了一下并且记录了下来,原文的地址是:https://stackoverflow.com/questions/35990538/extending-vs-implementing-a-pure-abstract-class-in-typescript/35990799#35990799</p>
<h2>问题描述</h2>
<h3 class="grid--cell fs-headline1 fl1 ow-break-word">Extending vs. implementing a pure abstract class in TypeScript</h3>
<p>假设我有一个干净的抽象类A:</p>
<div class="cnblogs_code">
<pre><span style="color: rgba(0, 0, 255, 1)">abstract</span> <span style="color: rgba(0, 0, 255, 1)">class</span><span style="color: rgba(0, 0, 0, 1)"> A {
    </span><span style="color: rgba(0, 0, 255, 1)">abstract</span> m(): <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)">;
}</span></pre>
</div>
<p>在继承(extends)方面,就像C#或者java里面那样,我可以像下面这样来继承这个抽象类:</p>
<div class="cnblogs_code">
<pre><span style="color: rgba(0, 0, 0, 1)"><span style="color: rgba(0, 128, 0, 1)">//<span style="color: rgba(0, 128, 0, 1)">TypeScript</span></span><br>class B extends A{<br>}<br></span></pre>
</div>
<p>但是在实现方面(implement),在TypeScript中也可以去implement一个类:</p>
<div class="cnblogs_code">
<pre><span style="color: rgba(0, 0, 255, 1)">class</span><span style="color: rgba(0, 0, 0, 1)"> C implements A {
    m(): </span><span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> { }
}</span></pre>
</div>
<p>那么问题来了:类B和类C在行为上有什么不同?我该如何选择?</p>
<h2>问题解答</h2>
<p>implements关键字将类A当作一个接口,这意味着类C必须去实现定义在A中的所有方法,无论这些方法是否在类A中有没有默认的实现。同时,也不用在类C中定义super方法。</p>
<p>而就像是extends关键字本身所表达的意思一样,你只需要实现类A中定义的虚方法,并且关于super的调用也会有效。</p>
<p>我想在抽象方法的情况下,这并没有什么区别。但是很少有只使用抽象方法的类,如果只使用抽象方法,最好将其转换为接口。</p>
<p>&nbsp;</p><br><br>
来源:https://www.cnblogs.com/pangjianxin/p/10901115.html
頁: [1]
查看完整版本: 【翻译】在TypeScript中,Extends和Implements一个抽象类有什么不同