Java Make sure the object implements the interface.

EDIT: enabled, see below

Hi,

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

Now, when you try to call a custom method on a shared object in Java, it tries to use typing. How can I somehow tell the compiler that my object implements this interface, so the method call is fine.

Basically, I'm looking for 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 this in Java?

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

 MyInterface obj; obj.resolve(); 

Sorry I did not think before publishing ....

+6
java interface
source share
3 answers

You just do it with the cast type :

 ((MyInterface) object).resolve(); 

It is usually best to check to make sure this actor is valid. Otherwise, you will get a ClassCastException . You cannot train everything that MyInterface does not implement into a MyInterface object. The way to perform this check is done using the instanceof operator:

 if (object instanceof MyInterface) { // cast it! } else { // don't cast it! } 
+3
source share
 if (object instanceof MyInterface) { ((MyInterface) object).resolve(); } 
+1
source share
 MyInterface a = (MyInterface) obj; a.resolve(); 

or

 ((MyInterface)obj).resolve(); 

The java compiler uses a static type to test methods, so you either need to pass the object to a type that implements your interface, or pass it to the interface itself.

+1
source share

All Articles