简体   繁体   中英

Actionscript overriding methods in extended interfaces vs Java?

I am much more familiar with Java's semantics of class and interface than with Actionscript semantics, but I have an example of some code that works in Java and doesn't work in Actionscript. This descrepency is a serious problem in that I am trying to code generate my Actionscript value objects from the Java DTOs and unless the semantics are the same, I am in deep trouble.

Here's the code that works in Java and fails to compile in Actionscript:

Interface A:

public interface Ia {
    function makeCopy():Ia;
}

Interface B:

public interface Ib extends Ia {
}

Class B (won't compile):

public class B implements Ib {
    public function makeCopy():Ib {
        return null;
    }
}

I don't understand why class B throws a compile error about an incompatible signature for "makeCopy" when clearly interface B extends interface A...thus there is no violation of type or incompatibility. If this is just an Actionscript limitation, can anyone suggest a way to recode?

NOTE: I already tried changing interface B to this and it threw an error in interface B (which work in Java):

public interface Ib extends Ia {
    function makeCopy():Ib;
}

From the context of ActionScript, the return type of makeCopy() has an incompatible signature.

Interface Ia defines makeCopy returning Ia.

Interface Ib extension would return Ia base from makeCopy. Adding makecopy():Ib to interface Ib is an incompatible override to the definition in Ia.

In class B, the incompatible signature expects makeCopy to return Ia.

Perhaps what you're trying to accomplish is more like an Abstract Class, where you should extend A and B classes.

In AS3, method signatures must be identical in both implementation and inheritance, so if you define the return type of makeCopy as Ia initially, that's how it must stay in all descendant interfaces and implementations thereof.

What you can do however, is return an instance of an object that implements Ib through a function signed with Ia , because it will still be a valid implementation of Ia :

public class B implements Ib {

    public function makeCopy():Ia {
        return this;
    }

    public function B() {
        trace(makeCopy() is Ia);  //true
        trace(makeCopy() is Ib);  //true
        trace(makeCopy() is B);   //true
    }
}

"makeCopy()" on the interface returns an Ia. Whereas in the implementation it returns an Ib. Unless an Ib is an Ia it is going to fail.

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