Question

I have something like this :

public interface MyInt {
  public void doStuff();
}

public extends SomeClass {
  // Some methodes
}

And then I would like to extends my class SomeClass. Now some of those sub-class could implements MyInt and therefore I would like to do something like :

List<SomeClass> list = new ArrayList<>();
// Then we put stuff in list
for (SomeClass s : list)
  if (s instanceof MyInt)
    s.doStuff();

But it doesn’t work. How can you use a method provided by an interface only if the latter is implemented by the current class ?

Have a nice day.

Was it helpful?

Solution

You're missing a cast to that interface in order to call its methods:

for (SomeClass s : list)
  if (s instanceof MyInt)
    ((MyInt) s).doStuff();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top