java - 多态性和接口(interface) - 澄清?

标签 java c# design-patterns interface polymorphism

(迂腐的问题)

根据 wikipedia有 3 种类型的多态性:

  • 临时多态性

refer to polymorphic functions which can be applied to arguments of different types, but which behave differently depending on the type of the argument to which they are applied

换句话说:重载:

function Add( x, y : Integer ) : Integer;
...
function Add( s, t : String ) : String;
  • 参数多态性

allows a function or a data type to be written generically, so that it can handle values identically without depending on their type

换句话说:泛型

示例:

class List<T> {
    class Node<T> { ...
  • 亚型多态性

allows a function to be written to take an object of a certain type T, but also work correctly if passed an object that belongs to a type S that is a subtype of T

(最常见的用法)

示例:

abstract class Animal {
    abstract String talk();
}

class Cat extends Animal {
    String talk() {
        return "Meow!";
    }
}
...

另一个例子:

class Animal
{
    public virtual void eat()
    {
        Console.Write("Animal eating");
    }
}
class Dog : Animal
{
    public override void eat()
    {
        Console.Write("Dog eating");
    }
}

太好了。

现在我想向您展示接口(interface)的定义:

Interfaces - An interface defines a contract that can be implemented by classes and structs. An interface can contain methods, properties, events, and indexers. An interface does not provide implementations of the members it defines—it merely specifies the members that must be supplied by classes or structs that implement the interface.

很好。

问题:

看看这段伪代码:

Dog implements IWalk {...}
Cat implements IWalk {...}
Array[IWalk] = [new Dog(),new Cat()]
foreach item in array :  item.walk();
  • 这是多态行为吗(在每个不同的对象上调用 walk())?

恕我直言,事实并非如此。为什么 ?因为它不对应于上述任何 wiki 类别。

我相信这是纯粹的编码原则,我通过不同的眼镜看一个对象——而不是像上面提到的 3 种范例那样创建/改变功能

我说得对吗?这是多态行为吗?

最佳答案

我认为您走在正确的轨道上。接口(interface)本身不是多态的。他们将多态性形式化。它们允许您以声明方式而不是实现方式定义多态行为。我喜欢将界面视为俱乐部中的保镖。他们只是确保每个人都遵循多态规则。

在您的示例中,实际的多态行为与接口(interface)本身无关,而是与共享的方法相关。 walk 方法适合子类型多态性示例。界面本身只是根据契约(Contract)要求子对象行走。

更新:

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

接口(interface)本身只是一个契约(Contract)(您在问题中明确指出)。多态性来自契约上的方法。 “多态类型是一种类型,其操作也可以应用于某些其他类型或类型的值”(来自维基百科)。接口(interface)(契约)是持有服务或使用方法(条款)的协议(protocol)。因此每个合约都包含多态行为的条款。

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

IWalk 
{
    void walk();
}

ITalk
{
    String talk();
}

IAnimal
{

}

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

在这种情况下,IAnimal 只是一个不包含多态行为的契约。 IWalk和ITalk提倡多态性。

关于java - 多态性和接口(interface) - 澄清?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25163683/

相关文章:

java - 如何将用户的 boolean 属性从 WMQ .NET 客户端 API 发送到 JMS?

java - 无法在已托管其他 Web 应用程序的 tomcat 中运行 Jenkins

c# - 在 WCF 可靠请求回复服务方法中回复时如何处理失败

c# - "C# base class virtual function"- "override in Managed C++ ref class"

ruby-on-rails - 递归更新两个相关对象图的模式

java - 使用sql比较java中的日期与当前日期

c# - Java 中的正则表达式匹配

c# - 从 Web 服务检索对象列表 C#

javascript - 使用事件在 View 设计模式之间进行通信

c - threadpools - 老板/ worker 与同行(工作人员)模型