Semantics - Passing an implemented interface into methods

Consider the following interface:

class MyInterface
{
   virtual bool test(void * param) = 0;
}

Can something like this implement an interface?

MyInterfacemyInterface = new MyInterface()
{
   bool test(void * param)
   {
        return true;
   }
}

myClass.setInterface(myInterface);

----- OR -----

myClass.setInterface( new MyInterface()
{
   bool test(void * param)
   {
        return true;
   }
} );

PS: This method runs in Java. Something like exsts in C ++ is interesting.

+4
source share
4 answers

The closest thing you can get in the java equivalent of an inline interface implementation is to put a private class in your compilation unit:

#include "MyInterface.hpp"

namespace {
    struct MyInterfaceImpl : public MyInterface {
        virtual bool test(void * param)
        {
            return true;
        }
    };
}

And use it elsewhere in this file (for example, from local instances of the stack).

+2
source

Java / . , - :

class Widget {
  std::function<void()> _callback;

  void setCallback(std::function<void()> callback) { _callback = callback; }

  void fireCallback() { if(_callback) _callback(); }
}

:

int main() {

     Widget *pw = new Widget();

     auto callbackFunction = []() { alert("called back!"); } // C++ lambda

     pw->setCallback( callbackFunction );
     ....
}

, Widget fireCallback, ( "back back!" ) .

+2

, - , Java, - , .

++ , Java. , , "" ( ) lambdas, , . , , ++, .

+1

, ++ . , .

- ( )

myClass::setInterface(MyInterface* ptr);
//or
myClass::setInterface(MyInterface& ref);

class MyInterfaceImpl : public MyInterface{
    //Stuff
}

MyInterfaceImpl setInterface, " " .

EDIT: - , πάντα ῥεῖ , , )

+1

All Articles