Geo
Geo

Reputation: 96897

question about java interfaces

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 ) ?

Upvotes: 1

Views: 213

Answers (6)

None
None

Reputation: 2947

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.

Upvotes: -1

ngn
ngn

Reputation: 7902

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.

Upvotes: 0

Fabian Buch
Fabian Buch

Reputation: 831

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.

Upvotes: 1

Frank Grimm
Frank Grimm

Reputation: 1171

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.

Upvotes: 0

Richard Walton
Richard Walton

Reputation: 4785

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

Upvotes: 0

Fernando Miguélez
Fernando Miguélez

Reputation: 11316

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).

Upvotes: 1

Related Questions