1

I'm trying to understand some interface implementation specifics and need some basic help. Given the next code:

public interface IGameObject
{
    Vector3 GetSomePosition();
}

public interface IPlayer : IGameObject
{
    void Die();
}

public class Player : GameObject, IPlayer
{
    void Die() { }
}

Can I implement the IGameObject interface in some other class instead of Player class and use the implementation of that other class? For example some special class called "GameObjectImplementation", that implements the IGameObject interface. Since I can't inherit from two classes, how do I go about this?

-----------------------------EDIT---------------------------

Best solution I found for now was to make a base class.

public abstract class PlayerBase : GameObject, IGameObject
{
    public Vector3 GetSomePosition()
    {
        return this.transform.Position;
    }
}

public class Player : PlayerBase, IPlayer
{
    void Die() { }
}

Any other suggestions? Like injection or some way of explicit implementations? Or is this the best way to do it already?

3
  • if GameObject implements IGameObject then you dont have to provide a further implementation in Player Commented Apr 17, 2015 at 8:13
  • You can implement multiple interfaces on some base class and extend it. On your code, you implemented GameObject class I think Commented Apr 17, 2015 at 8:15
  • The GameObject class comes from a library and does not have an interface for it's methods, that's the reason why I need to abstract away it's methods so I'm able to access it from other places. Will try a solution with an abstract class and additional inheritance. Commented Apr 17, 2015 at 8:58

1 Answer 1

3

If you mean something along these lines:

public class GameObjectImplementation: IGameObject
{
    public Vector3 GetSomePosition(){
       return null;
    }
}

public class Player : GameObjectImplementation, IPlayer
{
    public void Die() { }
}

then yes, you can. The Player class only inherits from GameObjectImplementation and implements IPlayer (directly) and IGameObject via the base class.

Also note that the implementing methods must be accessible from outside the class (e.g. public) because an inteface defines a contract, and only outwardly accessible things are able to fulfill that.

Sign up to request clarification or add additional context in comments.

1 Comment

Can't do that since the Player needs to inherit from GameObject (it's from a library).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.