An Interface with Abstract Methods

十年热恋 提交于 2019-12-02 19:24:22

问题


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);
?>

回答1:


All methods in an interface are abstract by definition.

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.




回答2:


No, it's not useful. He should either use abstract classes or just plain interfaces.

Interface methods are basically abstract anyway, so having abstract interface methods doesn't make much sense.



来源:https://stackoverflow.com/questions/4598555/an-interface-with-abstract-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!