对接口的质疑 [英] Doubts on Interfaces

查看:108
本文介绍了对接口的质疑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hello People

我对接口的问题很少:



1) - 接口和抽象类有什么区别? ?因为在我们两个都没有实现这些方法。我听说有人说它是一种契约,因为继承接口的类必须实现它的方法。但抽象类也是如此。

- 我看到的唯一区别是接口提供了多重继承的机制,因为不允许多次继承类。



2 ) - 为什么接口不包含访问修饰符?为什么它不包含静态或实例方法。但是我认为没有声明静态方法背后的原因是CLI。

- 符合公共语言基础设施的语言没有静态方法的接口,因此其他语言应该没有问题访问它们。



3)这是可能的:

接口i =  new  Class1();  ///  让我们说如果:Class1:Interface 
//
接口i =(接口) new Class1 (); /// /如果没有继承意味着Class1和继承之间没有关系,我已经完成了转换。





谢谢

解决方案

1。


您可以在抽象类中实现方法。区别在于:



接口:基本上是实现一组特定方法/属性的承诺(契约)。无论实现者创建的其他实现(其他方法,属性),这都定义了该类的基本接口(因此名称)。



摘要:这是一个基类实现。以Engine类为例,它具有一组定义的函数,如Start,Stop,Increase RPM,Decrease RPM等。这些方法可以实现(具体)。您还可以定义必须在派生类中实现(虚拟)的方法,因为在基础级别实现它们没有意义。您还可以定义可以作为基本实现保留的方法,也可以在派生类(抽象)中重写方法。



2.接口没有访问修饰符,因为根据定义,它们是public(编辑:public到类的实现者类和消费者,正如Sergey说的那样) ,接口本身可以用任何有效的访问修饰符标记,接口方法必须标记为public,但实现它的类也可以是任何更多或AS限制的修饰符作为接口,也就是说你不能实现内部接口在公共课上,试试吧)。拥有一个像protected或private这样的访问修饰符是没有意义的,因为你正在指示派生类的内部结构。接口只是一个类的外部接口,那么如何使外部类指定内部结构呢?这是更好地用于抽象类。



3.第一个是可能的,第二个是不可能的,除非继承流的Class1或其他东西实现接口。


让我们看看:



  1. 一般来说,诸如X和Y之间有什么区别之类的问题是不正确。 (苹果和苹果有什么区别?:-))有时,不可能给出差异的定义,概念本身可能是未定义的,有时它只需要定义,这可能很难。通常,差异仅适用于一些非常接近的事物。您添加了一些细节并删除了另一个细节,而不是可能不同。并非总是如此,所以最好避免这样的问题。



    那么,界面是否类似于抽象类?事实上,是和否。



    事实上,从历史上看,界面起源于抽象类的概念。如果你看一下COM接口,你会发现它们的功能是基于与某些类纯抽象类完全相同的内存布局,即没有字段的类,只有函数,所有函数都是纯虚拟。接口指针引用的类的二进制结构仍遵循相同的模式。



    但是,语义接口有很大不同。有一点是你提到的多重继承。这称为多重继承的弱形式。它引入了相当大的限制(与完全多重继承相比,读取弱点,同时消除了多重继承争议。购买方式,它也适用于上面提到的纯抽象类。



    .NET的另一个重要区别是: struct 类型无法派生,但它们可以实现接口,就像类一样。这意味着另一种更高级的多态性类型:首先,多态对象集不仅可以从具体类型中抽象出来,甚至可以从有关类型性质的知识中抽象出来:值类型的引用类型。由于多重继承,同一个对象可以同时成为不同多态集的成员,即使这些集基于不同的基类型(如果我可以使用与基类的类比),也就是说,定义多态集中成员资格的不同编译时类型。



    请注意,我的意思是广义上的多态性这个词。例如,接口类型的方法参数(或非密封类类型,对于此问题)定义了实际参数的一些有效运行时类型的多态集。请参阅:

    http://en.wikipedia.org/wiki/Polymorphism_%28computer_science %29 [ ^ ]。



    但真正的差异是代码设计中的不同角色。请看这些过去的答案:

    如何实现界面? [ ^ ],

    当我们使用摘要和使用时界面......? [ ^ ],
    抽象类和接口之间的区别,如果它们具有相同的no方法和var [ ^ ],

    如何决定选择抽象类或接口 [ ^ ],

    接口和多态性 [ ^ ]。
  2. 接口不需要访问修饰符。实际访问由实现类定义,并且对于接口的显式和隐式实现是不同的:

      interface  IFirst {
    void SomeMethod();
    }

    interface ISecond {
    void AnotherMethod ();
    }

    class 实现:IFirst,ISecond {
    void IFirst.SomeMethod(){ / * ... * / } // 显式,只能通过IFirst引用访问
    public void AnotherMethod(){ / * ... * / } // 隐式,公开访问
    }





    如果你可以在接口本身中指定这两种方法的访问权限,那就没有任何意义了。例如,如果访问可能是 private ,那么类可以如何接口? : - )

  3. 你可以做这些事情(但只有当类真正实现了接口,否则将抛出无效的强制转换异常),但它会在某种程度上破坏接口的目的。你最好避免这样的事情。预期的使用模式是不同的。使用上面给出的定义:

     IFirst first =  new  Implementation(); 

    // 从这一点开始,只能通过界面使用该对象:
    first.SomeMethod();
    // 或者,使用IFirst类型的形式参数,当运行时类型无法访问时:

    // ...
    void SomeMethodAcceptingAbstactParameter(IFirst first){
    // 那里无法访问实现类/结构的成员,甚至内部或公共成员:良好的封装
    }

    // 两用,有时候方便:
    实现实现= 实施();
    implementation.AnotherMethod();

    ISecond second = new Implementation();
    second.AnotherMethod(); // 但无法访问其他实施成员

  4. 总体而言,显式实现仅通过接口激发对象的使用,因此具有相当大的优点,但有时也需要隐含。如果某个基类已经使用某种虚方法实现了接口成员,你别无选择;你只能覆盖它。









请参阅我最近的回答,其中我详细解释了基于接口的多态性:没有超载和超载的多态性可能 [ ^ ]。



-SA


< blockquote>添加到已经说过的内容......



我看到的唯一区别是界面提供了多重继承的机制



接口与继承无关 - 完全不相关的类可以实现相同的接口。


Hello People
I have few questions on Interfaces:

1) - What is the difference between an interface and an abstract class? Because in both we dont implement the methods. I have heard people saying that it is a sort of a contract, because the class which inherits an interface will have to implement its methods. But the same goes with an abstract class.
- The only difference what i see is that interface provides a mechanism of multiple inheritance because multiple inheritance of classes are not allowed.

2) - why does an interface not contain access modifiers? also why does it not contain static or instance methods. However i think that the reason behind not declaring static methods is CLI.
- Common Language Infrastructure compliant languages dont have an interface with static methods so that other languages should have no problem accessing them.

3) is this possible:

Interface i = new Class1(); /// let us say if : Class1 : Interface
// and 
Interface i = (Interface) new Class1(); //// I have done casting if there is no inheritance that means no relationship between Class1 and Inheritance.



Thanks

解决方案

1.
You CAN implement methods in abstract classes. The difference is this:

Interface: Basically a promise (contract) to implement a particular set of methods/properties. No matter what other implementation the implementor creates (additional methods, properties), this defines a base interface to that class (hence the name).

Abstract: This is a base class implementation. Take for example an Engine class, it has a defined set of functions like Start, Stop, Increase RPM, Decrease RPM, etc. Those methods can be implemented (concrete). You can also define methods that must be implemented (virtual) in the derived classes because it doesn't make sense to implement them at the base level. You can also define methods that can either be left as the base implementation or overridden in the derived class (abstract).

2. Interfaces don't have access modifiers because they are, by definition, public (edit: public to the implementor classes and consumers of the class, as Sergey said, the interface itself can be marked with any valid access modifier, interface methods must be marked public, but the class that implements it can also be any modifier that is MORE or AS restrictive as the interface, aka you can't implement an internal interface on a public class, try it) . It doesn't make sense to have an access modifier like protected or private because you are then dictating the internal structure of the derived class. Interfaces are just that, an external interface to a class, so how do you make an external class dictate internal structure? Thats a better use for abstract classes.

3. The first one is possible, the second is not unless Class1 or something up the inheritance stream implements the interface.


Let's see:

  1. Generally speaking, the questions like "what's the difference between X and Y" are incorrect. (What is the difference between apple and Apple? :-)) Sometimes, it is impossible to give the definition of difference, the concept itself may be undefined, sometimes it just needs the definition, which can be difficult. Usually, "difference" only applies to some very close things. You added some detail and removed another detail, than it could be difference. Not always the case, so better avoid such questions.

    So, is interface similar to an abstract class or not? In fact, yes and no.

    Indeed, historically, interface originated from the concept of abstract class. If you look at COM interfaces, you will see, that their functionality is based on the memory layout fully identical to that of some class of "pure abstract classes", that is, the classes without fields, only with functions, and all functions are pure virtual. The binary structure of the classes referenced by interface pointers still follow the same schema.

    However, semantically interfaces are considerably different. One thing is the multiple inheritance you mentioned. This is called weak form of multiple inheritance. It introduce considerable limitation (read "weakness" compared to "full" multiple inheritance and at the same time removes multiple-inheritance controversies. Buy the way, it also applies to the "pure abstract classes" mentioned above.

    Another big difference in .NET is this: struct types cannot be derived, but they can implement interfaces, exactly as classes. It means another, more advanced type of polymorphism: first, polymorphic object sets can be abstracted not only out of concrete types, but even from the knowledge about the nature of the type: reference type of value type. Besides, due to multiple inheritance, the same object can be a member in different polymorphic sets at the same time, even if those sets are based on different "base types" (if I can use the analogy with "base classes"), that is, different compile-time types defining membership in a polymorphic set.

    Note that I mean polymorphism in the wide sense of this word. For example, a method parameter of interface type (or non-sealed class type, for this matter) defines some polymorphic set of valid runtime types of an actual parameter. Please see:
    http://en.wikipedia.org/wiki/Polymorphism_%28computer_science%29[^].

    But the real "difference" is the different roles in code design. Please see these past answers:
    How to realize interface?[^],
    When we use abstract and when we use interface...?[^],
    Difference between abstract class and interface if they have same no of methods and var[^],
    How to decide to choose Abstract class or an Interface[^],
    Interfaces and Polymorphism[^].
  2. Access modifiers are not needed for interfaces. The real access is defined by the implementing class and is different for explicit and implicit implementation of interface:

    interface IFirst {
       void SomeMethod();
    }
    
    interface ISecond {
       void AnotherMethod();
    }
    
    class Implementation : IFirst, ISecond {
        void IFirst.SomeMethod() {/* ... */} // explicit, only accessible via IFirst reference
        public void AnotherMethod() {/* ... */} // implicit, accessible publicly
    }



    If you could specify the access for these two methods in interfaces themselves, it would not make any sense. For example, if access could be private, how a class could be "interfaced"? :-)

  3. You can do things of these sort (but only if the class really implements the interface, otherwise invalid cast exception will be thrown), but it would defeat the purpose of interfaces, to certain extent. You should better avoid such things. The intended usage patters are different. Using the definitions given above:

    IFirst first = new Implementation();
    
    // from this point, use the object only through interface:
    first.SomeMethod();
    // or, you use the formal parameters of IFirst type, when the runtime type it not accessible:
    
    //...
    void SomeMethodAcceptingAbstactParameter(IFirst first) {
        // there is no a way to access members of implementing class/structure, even internal or public ones: good encapsulation
    }
    
    //dual use, sometime handy:
    Implementation implementation = new Implementation();
    implementation.AnotherMethod();
    
    ISecond second = new Implementation();
    second.AnotherMethod(); // but no access to other Implementation members

  4. Overall, explicit implementation stimulates the use of the object only through the interface and thus has considerable advantages, but sometimes implicit is also needed. And you have no choice if some base class already implemented interface member using some virtual method; you can only override it.



[EDIT]

Please see my recent answer where I explained polymorphism based in interfaces in detail: POLYMORPHISM WITHOUT OVERLOADING AND OVERRRIDING IS POSSIBLE[^].

—SA


To add to what was already said...

"The only difference what i see is that interface provides a mechanism of multiple inheritance"

Interfaces have nothing to do with inheritance -- classes that are totally unrelated can implement the same Interface.


这篇关于对接口的质疑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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