Java block in constructor method call

// allows passing in arguments to the MyActor constructor ActorRef myActor = system.actorOf(new Props(new UntypedActorFactory() { // public UntypedActor create() { // return new MyActor("..."); // <- this part confuses me } // } // ), "myactor"); 

I am new to Java by looking at the Akka documentation. and I find the code shown is confusing. Especially the code block below. How a block of code can be sent to the call "new UntypedActorFactory ()". What is called the type of constructor initialization.

 { public UntypedActor create() { return new MyActor("..."); } 
+4
source share
2 answers

The part that confuses you creates an anonymous class, then instantiates and passes the newly created instance to the method as an argument. The block of code you are referring to is the body of an anonymous class that is derived from UntypedActorFactory

For example, if you have an interface:

 interface SomeInterface { void someMethod(); } 

You can create an anonymous class that implements your interface like this (similar syntax is suitable for extending named classes):

 SomeInterface instance = new SomeInterface() { public void someMethod() { // // implementation here // <- similar to the example, } // this is the body of anonymous class }; // 
+4
source

This is an anonymous class.

This is just a new class inheriting from UntypedActorFactory with a declared method.

0
source

All Articles