且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

多态性和接口 - 澄清?

更新时间:2023-01-17 11:07:55

我认为你是在正确的轨道上.接口本身不是多态的.它们形式化了多态性.它们允许您以声明的方式定义多态行为,而不是实现.我喜欢把 Interfaces 想象成俱乐部里的保镖.他们只是确保每个人都遵循多态规则.

I think you are on the right track. Interfaces are not polymorphic themselves. They formalize polymorphism. They allow you to define polymorphic behavior in a declarative way, instead of implementation. I like to think of Interfaces as the bouncers in the club. They just make sure everyone is following the polymorphic rules.

在您的示例中,实际的多态行为与接口本身无关,而是与共享的方法相关.walk 方法适合子类型多态性示例.接口本身只是根据合同要求子对象行走.

In your example the actual polymorphic behavior isn't related to the interface itself but the method that is shared. The walk method fits the subtype polymorphism example. The interface itself just contractually obligates the child objects to walk.

更新:

基于评论:为了清楚起见 - 通过对象实现的不同接口查看对象 - 也是多态行为?

based on comment: just to make it clear - looking at an object via different interfaces it implements - is also polymorphic behaviour ?

界面本身只是一个合同(您在问题中指出).多态性来自合约上的方法.多态类型是一种其操作也可以应用于某些其他类型或类型的值的类型"(来自***).接口(合同)是保存服务或使用方法(条款)的协议.所以每个合约都包含多态行为的条款.

The interface itself is just a contract (which you nailed in your question). The polymorphism comes from the methods on the contract. "A polymorphic type is a type whose operations can also be applied to values of some other type, or types" (from wikipedia). The interface (contract) is the agreement that holds the methods (terms) of service or use. So each contract hold the terms that are the polymorphic behavior.

Dog implements IWalk, ITalk, IAnimal
{
    //concrete implementation
}

IWalk 
{
    void walk();
}

ITalk
{
    String talk();
}

IAnimal
{

}

我对 java 生疏了,所以如果它在语法上不正确,请考虑这个伪代码.

I am rusty on java so consider this pseudocode if its not syntactically correct.

在这种情况下,IAnimal 只是一个不包含多态行为的合约.IWalk 和 ITalk 促进了多态性.

IAnimal in this case is just a contract that does not contain polymorphic behavior. IWalk and ITalk promote polymorphism.