Anonymous classes

故事扮演 提交于 2019-12-23 12:42:28

问题


In Java, it's common to write the following (e.g. for event handling) in order to make use of the template method pattern:

abstract class SomeAbstractClass {
    public abstract void SomeFunction ();
}

//...

SomeAbstractClass obj = new SomeAbstractClass () {
    public void SomeFunction () { /* implementation */ }
};

In C++, the following compiles:

class SomeAbstractClass {
    virtual void SomeFunction () = 0;
};

// ...

SomeAbstractClass * obj = new ( class : public SomeAbstractClass {
    virtual void SomeFunction () { /* implementation */ }
});

Why don't people do this usually?


回答1:


Three problems i think occurs with anonymous class

  • You cannot write a constructor as class doesn't have a name.
  • initializer list inheritance is not allowed.
  • capturing value is also difficult, final variable are accessible only.


来源:https://stackoverflow.com/questions/18171684/anonymous-classes

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