Home > OS >  How to use a method from another class if both classes implement the same interface
How to use a method from another class if both classes implement the same interface

Time:12-29

So here's an example of what I'm trying to do:

 public interface IFlyable
    {
        void Fly();
    }
    internal abstract class Insect { }
    internal class Bee : Insect, IFlyable
    {
        public void Fly()
        {
            //some implementation
        }
    }
    internal class Hornet : Insect, IFlyable
    {
        public void Fly()
        {
            //here I want the same implementation as in Bee.Fly()
        }
    }

As a complete newb not wishing to just copy-paste the implementation, the only meaningful way I could come up with was to make another asbtract class for flying insects and inherit everything needed from there:

internal abstract class Insect { }
internal abstract class FlyingInsect : Insect, IFlyable
{
 public void Fly()
 {
    //implementation
 }
}
internal class Bee : FlyingInsect
{

}
internal class Hornet : FlyingInsect
{

}

Even though this solves my problem, still I would like to know what could be better and alternative ways of doing this, especially if there's a way that allows to not create another "unifying" class, but instead calling/taking this already implemented method from another class that uses the same interface. Thanks in advance.

CodePudding user response:

It depends on what coupling you want, but your choice of an intermediate class seems reasonable if all flying insects will use that implementation (or just a few don;t, and you can override it as necessary). Here are a few other options:

  • Add an internal method to Insect that Bee and Hornet both call (this seems a little weird if it only applies to flying insects, though)
  • Add a static method to Bee that Hornet calls (Bee.Fly would have to call it as well)
  • Add a static method in some other location (a "utility" or "helper" method?) that both call.

Note that there's not a "clever" way to automatically call some other class's implementation just because they implement the same interface. An intermediate type to implement shared behavior seems like the best choice at face value.

  • Related