forsberg forsberg - 2 months ago 5x
Java Question

Method's param - requiring both a class and interface at the same time

I have a class Context. It's required to be passed to and used in an another class'es constructor - called, say, Manager. But the context variable must be also an implementation of MyInterface, which obligates to implement a requiredMethod(). So I wanted to be something like:

class Manager {
Manager(Context context) {
if (context instanceof MyInterface) {

However, a compilator and IDE tell me that requiredMethod() cannot be solved.

So am I obliged in order to solve this issue to create an "artificial" another class, which extends from Context class, and implements MyInterface - just in order to use it as a single object in the constructor above? Or there's a better solution to do this?


This checks if the variable is an instance of the type at runtime:

if (context instanceof MyInterface)

But it doesn't resolve the variable to that type at compile time. To do that, you can cast it:

if (context instanceof MyInterface) {