0

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

2
  • 2
    Does Rook also define a field named color? I would guess you have a shadowing field named color. Unfortunately, your screenshot does not show enough of the code to be sure. Nor did you post a minimal, reproducible example. So I can only guess. Commented Apr 15, 2020 at 4:07
  • @ElliottFrisch sorry about the lack of information, both Rook and GenericPiece have the same 2 instanced variables: color and position Commented Apr 15, 2020 at 4:10

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Is it convention to use either only public or only protected access in super classes? Or is in inconsequential?
You should follow the Principle of Least Privilege. This means that members should be assigned the minimum accessibility needed for the program to work. If an unrelated class needs access, make it public. If only subclass class needs access and is the only trusted..make it protected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.