Override Object.toString Error

橙三吉。 提交于 2019-12-08 18:33:30

问题


Why does this produce an error in Flash Builder?:

package {
  public class Foo {
    override public function toString():String {
      return "Foo";
    }
  }
}

Tab completion suggests that this is available for override...

Error message:

Multiple markers at this line:
-public
-1020: Method marked override must override another method.
-overridesObject.toString

回答1:


Remove override on the toString() method.

There is a popular misconception among about the toString() method, namely: if one wants to provide a custom implementation of a super class method, the override keyword is needed. But in case of Object, toString() is dynamic and is attached at runtime, negating the need for overriding. Instead, the implementation is to be provided by the developer so one is not created at runtime. One just needs to write their own toString():String implementation.




回答2:


Foo is not extending a class; so therefore there are no methods to override. Just remove the override keyword from the function definition and it should compile

package {
  public class Foo {
    public function toString():String {
      return "Foo";
    }
  }
}

I'll add that toString() is a method of the Object class which many ActionScript classes extend from. But, even if you extend Object, you don't need to override the toString() method. From the docs:

To redefine this method in a subclass of Object, do not use the override keyword.

Like this:

package {
  public class Foo extends Object {
    public function toString():String {
      return "Foo";
    }
  }
}


来源:https://stackoverflow.com/questions/18347026/override-object-tostring-error

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