Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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;
    }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

To differentiate between the parameter and the instance variable

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading