I have a class constructed like that:
public class Creature
{
protected final AI ai;
// ...about 10 other objects
public Creature (CreatureType type, int x, int y)
{
ai = new AI ();
// some other code
}
// ... many methods
}
My class AI will be an artificial intelligence of the creature. I would like it to have full access to the Creature object as if it was inside. How could I achieve that? By some tricky way to inherit it?
2
Answers
Making AI an inner class of Creature would give AI access to Creature’s instance variables.
See: http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
You can do it in a few ways:
Creature
and doesn’t have to interact with other classes directlyAn improvement to the first approach will be to use DI (dependency injection) and pass an AI object to the constructor instead of initializing the object (using
new
) in it.I see that you added in the comments: “my class AI will handle many operations for lots of creatures”. In order not to end up with a huge AI class that’ll be tightly coupled with many creatures, I would create an AI interface and an AIService which will expose an interface with the supported operations. This service will be responsible to call the right AI implementation (per Creature type) to handle the operations.