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

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

问题描述

我遇到了一些由同事编写的 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天全站免登陆