Jake
Jake

Reputation: 71

Java - Make sure an object implements an interface

EDIT: Solved, see below

Hi,

In Java, I got an object that could be of any class. BUT - that object will always have to implement an interface, so when I call methods defined by the interface, that object will contain that method.

Now, when you try to call a custom method on a generic object in Java, it mucks about typing. How can I somehow tell the compiler that my object does implement that interface, so calling the method is OK.

Basically, what I'm looking for is something like this:

Object(MyInterface) obj; // Now the compiler knows that obj implements the interface "MyInterface"
obj.resolve(); // resolve() is defined in the interface "MyInterface"

How can I do that in Java?

ANSWER: OK, if the interface is named MyInterface you can just put

MyInterface obj;
obj.resolve();

Sorry for not thinking before posting ....

Upvotes: 6

Views: 3482

Answers (3)

Kaleb Brasee
Kaleb Brasee

Reputation: 51965

You just do it with a type cast:

((MyInterface) object).resolve();

Usually it is best to do a check to make sure that this cast is valid -- otherwise, you'll get a ClassCastException. You can't shoehorn anything that doesn't implement MyInterface into a MyInterface object. The way you do this check is with the instanceof operator:

if (object instanceof MyInterface) {
    // cast it!
}
else {
    // don't cast it!
}

Upvotes: 3

josefx
josefx

Reputation: 15656

MyInterface a = (MyInterface) obj;
a.resolve();

or

((MyInterface)obj).resolve();

the java compiler uses the static type to check for methods, so you have to either cast the object to a type which implements your interface or cast to the interface itself.

Upvotes: 1

Bozho
Bozho

Reputation: 597422

if (object instanceof MyInterface) {
    ((MyInterface) object).resolve();
}

Upvotes: 1

Related Questions