(RMI) Why Is the Naming.lookup object cast as an Interface ?

Nikolas Nikolaou

Ranch Hand

Posts: 101

1

posted 3 years ago

Hi.I'm reading about RMI In Head First Java and I'm a bit confused about the Naming.lookup method.I understand that It returns an object.Why Is this Object cast to an Interface and then a method Is run from the Interface.I thought Interfaces could not have methods with bodies.

Ulf Dittmer

Rancher

Posts: 42972

73

posted 3 years ago

It is cast to an interface because the exact type (class and package name) may not be known, and should not matter in any case. The important point is that the object being looked up implements a particular interface, and thus it is know what methods can be used.

Remember that an interface is just a conceptual device - you always invoke methods on objects, not on interfaces, even if the reference you happen to have has the type of an interface.

Nikolas Nikolaou

Ranch Hand

Posts: 101

1

posted 3 years ago

Thanks for replying. That makes sense!
I have one more question.Am I right In saying that the "MyRemote" class doesn't have to be In the same package as "MyRemoteClient" when you are using an = and not Instantiating a new object ?