-1

Similar to how you can cast down the hierarchical chain (assumption), I wish to do something similar but with Interfaces.

There is a parent class "A", and a bunch of child-classes of "A". However, the sub-set of child-classes I am dealing with all implement some interface. However, not all child-classes do, just the ones I happen to be working with.

So the method signature looks something like this:

public void action(A a) {
}

So, that the method can do something with anything that is type "A" or a child of it, however, the only ones I am interested in all happen to implement the same interface.

So, I want a way to be able to assume (or cast?) the interface so I can call one of the interfaces methods.

So something like:

public void action(A a) {
    ((B) a).methodFromB(); // ((Interface) a).methodFromInterface();
}

However, instead it would be an interface that I know the specific object I am working with implements.

Dylan Holmes
  • 83
  • 1
  • 5
  • 2
    Yes, you can cast to an interface type. There's a mechanism to tell if an object is an [instance of](https://stackoverflow.com/questions/7313559) a class that implements that type. When possible, it's preferable to use polymorphism. – Andy Thomas Apr 22 '19 at 22:54
  • 1
    If all you care about are the classes which implement `B`, why even have a parameter of `A`? – Makoto Apr 22 '19 at 22:56

1 Answers1

0

Thanks to Andy Thomas, turns out you can just cast to an interface type.

((InterfaceName) objectThatImplInterface).methodFromInterface();
Dylan Holmes
  • 83
  • 1
  • 5