Home > Software engineering >  Why do I need a "this" reference in a constructor but not the methods below?
Why do I need a "this" reference in a constructor but not the methods below?

Time:05-26

If I don't include this references in the constructor, I get the error "The assignment to variable [x] has no effect java." However, I have no problem not using one in the get method written below. Why is that?

public class Bicycle {
    
    private String brakeType;
    private int numGears;
    private int numWheels;
    
    // Constructor
    public Bicycle(String brakeType, int numGears, int numWheels) {
        this.brakeType = brakeType;
        this.numGears = numGears;
        this.numWheels = numWheels;
    }
    
    // Get methods
    public String getBrakeType() {
        return brakeType;
    }

CodePudding user response:

The parameters are shadowing the fields. That is the reason, why do you need this.
Otherwise the compiler didn't know if you mean the field brakeType or the parameter brakeType.

CodePudding user response:

To differentiate between the parameter and the instance variable

  • Related