简体   繁体   中英

Java constructor in agregation subclass

I have recently learnt the use of subclasses and I am creating a Java game. I have a superclass CHARACTER which is the character of the game. This class has many subclasses like SOLDIER and FARMER. Now I need to have a subclass called GROUP, which is a bunch of characters.

The superclass constructor is the following:

public Character (String id,Position p);

How can I create the constructor of the subclass GROUP, which has to call the super constructor N times?

How can I create the constructor of the subclass GROUP, which has to call the super constructor N times?

You can't. And you don't need to.

Each Java class has exactly one superclass. And each object of a class has only one state of its superclass.

Fortunately, your Group class does not have to call the super constructor N times. Either a Group is a Character or not. If it is a Character, it is one character. You call the Group's super constructor one time.

Regardless, the Group contains characters. The super constructor of a Soldier or Farmer is called from the constructor for the Soldier or Farmer -- not from the Group/s that contain the character.

For example, your Farmer class might look like this:

public class Farmer extends Character {
   public Farmer(String id,Position p) {
      super( id, p ); // <-- Superclass constructor for one farmer.
      ...
   }
   ...
}

And your Group class might look like this, if a Group is a Character:

class Group extends Character { 
    private Collection<Character> m_members;
    Group( String id,Position p, Collection<Character> members ) {
        super( id, p ); // Superclass constructor for the *group*.
        m_members = new ArrayList<>( members ); // Defensive copy
    } 
}

Or this, if it's not.

class Group  { 
    Group( Collection<Character> members ) {
        m_members = new ArrayList<>( members ); // Defensive copy
    }
}

Your group should rather be an array, a list or similar. Then you instantiate via a loop.

CHARACTER[] group = new CHARACTER[10];
for (int c = 0; c < 10; c++) group[i] = new CHARACTER(id, position);

That way you also can access the members easily. Becaues FARMERS and SOLDIERS are subclassed to CHARACTER,

CHARACTER[] group = new CHARACTER[10];
for (int c = 0; c < 10; c++) group[i] = new SOLDIER(id, position);

Will also work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM