与抽象方法的接口 [英] An Interface with Abstract Methods

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

问题描述

我遇到了一些由同事编写的PHP代码(它没有用于任何东西)。基本上它是一个包含抽象方法的接口。然后我说这是愚蠢的,并显示另一位同事坐在我旁边。我们笑了,但后来开始互相询问是否有可能,如果是的话,它是否真的有用。显然这是不可能的(见下面的例子),但如果有可能会有用。

I came across some PHP code that was written by a co-worker (it was not used for anything). Basically it was an interface containing abstract methods. I then said that this was stupid and showed another co-worker sitting next to me. We laughed but then started to ask each other if it was possible and if so if it was actually useful. Apparently it is not possible (see example below), but if it was possible would it be useful.

您能想到这可能有用的情况吗?

Can you think of situations where this could be useful?

<?php
    interface Itest
    {
        abstract public function add(int $x, int $y);
    }

    abstract class ParentTest implements Itest
    {
        abstract public function add(int $x, int $y);
    }

    class test extends ParentTest
    {
        public function add(int $x, int $y)
        {
            return $x+$y;
        }
    }

    $w = new test;
    echo $w->add(5,8);
?>


推荐答案

接口中的所有方法都是抽象的定义。

抽象方法是提供原型但未实现的方法。它强制子类实现它,或者声明为抽象。

An abstract method is a method for which the prototype is supplied but not implemented. It forces subclasses to implement it, or be declared abstract.

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

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