I have a question regarding interfaces. I have a interface that has all the methods of a class called GameWorld. The GameWorld holds a class called GameObject that can be tanks, rocks, missiles, etc.
public interface IGameWorld
{
public Point getLocation(); // GameObject
public Color getColor();
public void setLocation(Point newCoord);
public void setColor(Color newColor);
}
I want to implement the methods in IGameWorld in GameWorld's GameObject class. Something like this.
public class GameWorld implements IGameWorld
{
// vector to hold gameobjects
public class GameObject
{
private Point location;
private Color color; // all objects have a random color
GameObject()
{
// method
}
public Point getLocation()
{
// method
}
public Color getColor()
{
// method
}
public void setLocation (Point newCoord)
{
// method
}
public void setColor (Color newColor)
{
// method
}
}
}
Is that possible? And if not, what is the alternative to doing this? Thanks.
-
1That is what interfaces are for isn't it?Antoniossss– Antoniossss2013年10月30日 06:34:03 +00:00Commented Oct 30, 2013 at 6:34
3 Answers 3
You make instances/objects of classes. No need to define a separate class which represent your object. Anyway what you have done is wrong because class GameWorld implements IGameWorld and GameWorld must implement all the methods and not GameObject class.
You can remove GameObject class
public class GameWorld implements IGameWorld
{
private Point location;
private Color color; // all objects have a random color
public Point getLocation()
{
// method
}
public Color getColor()
{
// method
}
public void setLocation (Point newCoord)
{
// method
}
public void setColor (Color newColor)
{
// method
}
}
and then make instances/objects of this concrete class
IGameWorld gameObject = new GameWorld();
1 Comment
To above answer I would like to add that using interfaces makes our code as loosely coupled. So instead of using GameObject use interface where ever you need.
And your interface defines the common methods which are required for all the classes to create game and hence we can use as:
IGameWorld marioGame = new GameWorld();
IGameWorld tankGame = new GameWorld();
etc.
Comments
I don't think your GameObject class should be inside your GameWorld class. Try making them public classes in separate files. Then, only GameWorld will implement IGameWorld and your other classes (you mentioned tanks, rocks, missiles, etc.) will extend GameObject.