John Zamoider
John Zamoider

Reputation: 35

Java object in object

I want to keep as many things in separate java files for code readability and for debugging issues.

I have a java class Called Actor. The Actor class is designed to be an object that holds all the Actor's(as in the Object created from the class Actor information, but also be used for other things, like monsters, ect.

Another class called Status. This class takes care of all the status ailments and will modify the attributes to the Actor (Example: if they are stunned).

I want this Status Class to be a part of Actor, without nesting the classes. Is this possible?

Upvotes: 3

Views: 78

Answers (2)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285450

You are right -- you shouldn't nest inner classes or inheritance for this. The problem is readily solved with composition: Give the Actor class a Status field with getter and setter methods.

public abstract class Actor {
  private Status status;

  public Actor() {
    status = new Status(); // default empty status
  }


  public Actor(Status status) {
    this.status = status;
  }

  public void setStatus(Status status) {
    this.status = status;
  }

  public Status getStatus() {
    return status;
  }
}

Edit

Clarification: I recommend a solution that uses inheritance, since many classes will inherit Actor, but one that does not try to mis-use inheritance by having either Actor extend Status or Status extend Actor.

Upvotes: 3

Nathua
Nathua

Reputation: 8836

class Actor{

   private Status mStatus;

   public void stun(){}
}

Composition will help you

Upvotes: 2

Related Questions