The interface being implemented is either declared within the code module (file) where implementation occurs, or in an external .class file, which is imported through the import statement. This all usually takes place in the absence of COM.
You cannot define an interface using the interface declaration and import the same interface's declaration from a .class file. This rule is also true for COM interfaces: they are not defined by Java. Instead, a COM interface is defined in a .idl file, compiled into a type library, and then imported into Java as though it were a standard Java .class file.
To implement COM interfaces on a Java class, use the implements modifier in the class declaration with a list of interface names, and provide method bodies for each method in the interfaces (excluding QueryInterface, AddRef, and Release).
The following example shows the IRobot COM interface described in a .idl file:
[ object, uuid(6C6971D5-8E69-11cf-A54F-080036F12502)] interface IRobot : IUnknown { ... HRESULT OutputStatusMessage([out, retval]BOOL* pRetVal); ... };
If the .idl file was compiled into the robocorp/bots.tlb type library, the following Java code could be written to implement a Robot object:
import robocorp.bots.*; class RogerRobot implements IRobot { ... boolean OutputStatusMessage(void) { return VoiceBox.Speak(CurrentStatus()); } ... }
Every Java class automatically implements IUnknown and IDispatch. The dispinterface implemented by the IDispatch interface, which Java provides, contains the public methods that are on the default interface for the class. For example, the following Java class implements an IDispatch interface, which supports MethodA and MethodB:
class Example { public void MethodA(void) { ... } public void MethodB(int x) { ... } }
At runtime, the Microsoft VM automatically provides type information for this IDispatch implementation (using IDispatch::GetTypeInfo), so clients can avoid the overhead of using IDispatch::GetIDsOfNames to do late binding. Because all Java objects are COM objects, nothing else is required.