tags:

views:

145

answers:

6

Let's say I have the following ruby code :


def use_object(object)
  puts object.some_method
end

and , this will work on any object that responds to some_method,right?

Assuming that the following java interface exists :


interface TestInterface {
   public String some_method();
}

Am I right to presume that interfaces are java's way to achieving the same thing ( with the only difference that the parameter's type would be TestInterface ) ?

+1  A: 

You are right except that you can not define the body of a function in Java Interfaces, only prototypes.

Interfaces are the only way to implemente a pseudo multi-derivation in Java, since normal class derivation is only simple (just one parent).

Fernando Miguélez
A: 

Java interfaces define method signatures which an implementing class must provide. The JavaDoc explains all this in great detail.

Richie_W
A: 

In Java interfaces can only be used to declare methods, not the define (implement) them. Only classes can implement methods. But classes can implement interfaces. So you could for instance use the Adapter pattern to realize the same thing you did in ruby.

Frank Grimm
+1  A: 

No, interfaces in are not implemented. You can have multiple implementations of it though.

An interface would look more like:

interface TestInterface {
   public String some_method();
}

And it could be implemented in a class:

public class TestClass implements TestInterface {
   public String some_method() {
       return "test";
   }
}

And maybe more classes that implement this method differently. All classes that implement an interface have to implement the methods as declared by an interface.

With interfaces you can't achive exactly the same as in your Ruby example since Java is static typed.

Fabian Buch
A: 

Yes, but only if you want to abstract out "anything having a some_method()" as a separate concept. If you only have one class that has some_method(), you need not specify an interface, and the parameter of use_object() will be that class.

Note also, that in Java we use camelCase instead of underscore_separated names.

ngn
I wanted to have the same name for the method in both languages .
Geo
A: 

It look like you are trying to program in Ruby using Java, you want want to rethink your approach to use more the idioms of the language.

Mark Lubin