skip to Main Content

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


  1. 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

    Login or Signup to reply.
  2. You can do it in a few ways:

    • Inclusion: which is what you did, only that you should pass local variables and class variables to AI methods (separation of concerns etc). That’s also my favorite approach.
    • Inheritance: makes sense to do only if there’s a relation between the classes
    • Inner class: makes sense if AI is relevant only to Creature and doesn’t have to interact with other classes directly
    • put the classes in the same package and set the relevant access modifiers to be package-private

    An 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search