Home > Enterprise >  Is it bad practice to make a super class composed of its inherited subclass?
Is it bad practice to make a super class composed of its inherited subclass?

Time:03-08

I have 2 classes, a player and a weapon. Both have an hp instance (represents durability for weapon) and a "name" instance. So If I want to access the hp of the weapon, I don't have to re-create a getHp method in the weapon class, since it is already in the player class. That's inheritance. However, I also want a weapon to be in the player constructor. So thats composition of the subclass. The problem is, the weapons class has to inherit the weapon object in the player constructor, so I just put null, in super().

public class Player {

    private int hp;
    private String name;
    private int speed;

    
    private ArrayList<Weapon> wList;  //There is a list of weapons in the player class
   



    public Player(int h, Weapon w, String n, int s) {

        hp = h;
        name = n;
        currentW=w;
        speed=s;


        wList = new ArrayList<>();
       public int getHp() {
        return hp;
    }

    public String getName() {
        return name;
    }

    }
public class Weapon extends Player {
    private int damage;
   

    public Weapon(int h, String n, int damage) {
        super(h, null,n, 0)
        this.damage = damage;
      

    }

If this is bad practice, is there another way to have weapon in the player constructor, but not have to re-write the getter methods?.

CodePudding user response:

Yes, this is a bad practice. Such architecture will lead to very hard to follow code. What you need to do is create an Abstract class and move some of the information to that and have both your Weapon and Player class extend that.

public abstract class AbstractHealthObject {
   private String name;
   private int hp;

   public AbstractHealthObject(String name, int hp) {
     setName(name);
     setHp(hp);
   }
   //add getters and setters
}

public class Player extends AbstractHealthObject {
   //instance variables
   public Player(int h, Weapon w, String n, int s) {
     super(h, n);
     //set instance variables
   }
}

public class Weapon extends AbstractHealthObject {
   public Weapon(String name, int hp, int damage) {
     super(name, hp);
     //set instance variables
   }
}
  • Related