C#接口类继承VS纯抽象类
作者:互联网
这种OOP方法注定要失败吗?还是有一些优点?
在我理解抽象类之前,我通过使用接口类(实现了接口的某些方法的常规类)而获得了代码重用的大致相同的好处.例如
public interface IMyService
{
String Helloword1();
String Helloword2();
String Helloword3();
}
public class MyService
{
public String Helloword1(){return "1";}
public String Helloword2(){return "2";}
//Helloworld3 is not here so I would be forced to provide implementation in any subclass
//very similar to calling abstract on a method
}
public class SubClass1: MyService, IMyService
{
public String Helloword3(){return "3";}
}
public class SubClass2: MyService, IMyService
{
public new String Helloword2(){return "override method";}
public String Helloword3(){return "3";}
}
谁能看到这样做的好处,还是真的提供与抽象类相同的好处?
解决方法:
Can anyone see of any advantage of doing this or is this really providing the same advantages as an abstract class?
这样做有很大的缺点.您可以允许人们在不实现Helloword3的情况下继承MyService的子类,因为这不是合同的一部分.
一个抽象类将强制该类型实现该成员.在这里,您相信用户将实现“必需”界面.
标签:oop,polymorphism,interface,c,abstract 来源: https://codeday.me/bug/20191029/1958480.html