简体   繁体   中英

Extending interfaces changing method signature

Consider the following interfaces

interface Foo1
{
    public function foo(BaseClass)
}

and

interface Foo2
{
    public function foo(SpecialClass)
}

where SpecialClass inherits from BaseClass .

Now, a Foo1 instance could be used whenever a Foo2 instance is required. I mean, if I need an object with a foo method that accepts a SpecialClass , I could do the job with an object with a foo method that accepts a BaseClass .

Hence I would like to be able to declare Foo1 as a sublclass of Foo2 (ie Foo1 extends Foo2 ).

In PHP (the language I usually work with) this is not possible and would produce a fatal error.

As far as I know this is feasible in Java, but would require to implement a specific foo method taking a special class as argument (am I wrong on this?).

Does all this make sense or am I missing something? Is there any other object oriented language that provides this out of the box?

In java syntax the interface should be declared as following:

interface Foo2
{
    public void foo(SpecialClass b);
}

interface Foo1 extends Foo2
{
    public void foo(BaseClass s); // In Java doesn't inherits from Foo2.foo!
}

The above script is theoretically correct from inheritance perspective. Unfortunately, Java don't interprets it in the expected way: Foo1.foo and Foo2.foo are considered two different overloaded functions.

The only declaration accepted and interpreted by Java in the expected way is the following:

interface Foo2
{
    public void foo(BaseClass b);
}

interface Foo1 extends Foo2
{
    public void foo(BaseClass b);
}

And then you can write in your own implementation something like:

class Foo1Class implements Foo1
{
    public void foo(BaseClass b)
    {
        if(!(b instanceof SpecialClass)) throw new ClassCastException();

        ...
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM