this Keyword

AP Computer Science A· difficulty 3/5

public class Box {
    private int width;
    public Box(int width) {
        width = width;
    }
}

What is wrong with the constructor?

  • A

    Nothing is wrong

  • B

    private fields cannot be set in a constructor

  • C

    The parameter shadows the field; assignment has no effect on the field

    check_circle
  • D

    Constructors cannot have parameters

Explanation

The parameter width shadows the instance field of the same name. The assignment width = width copies the parameter to itself; it should be this.width = width.

Want 10 more like this — adaptive to your weak spots?

Related questions