Search code examples
javainheritanceconstructorsuperclass

Java how to set child class instance variable with super class constructor


I have a child class with two instance variables color and position. The constructors takes in both of these. I first call the super(color) constructor which contains setColor(color)->this.color = color. According to debugging tool, this is setting this.color for the super class rather than the child class which invoked the method. Is this not the proper method of using a super class constructor to set instanced variables?

Rook.java:

public Rook(String color, Position pos) {
    super(color);
    // at this point this.color == null (for Rook)
    initPosition(pos);
}

GenericPiece.java:

public GenericPiece(String color) {
    setColor(color);
    // at this point this.color == "white" (for GenericPiece)
}

public void setColor(String color) throws InvalidPieceColorError {
    if (Color.checkValid(color)) {
        this.color = color;
    } else {
        throw new InvalidPieceColorError(color);
    }
}

!Here's a picture of debugging information1


Solution

  • The color field should only be part of the parent class and not duplicated inside the child one. Inheritance is about shared state so color will be inherited by the Rock type and will have public or protected access.