Search code examples
javaclassparametersconstructorproperties

Do the parameters of a constructor in Java have any connection with the properties of the class?


I'm confused...

package car;

public class Car {

    private String color;
    private int maxSpeed;
    private String brand;

    public Car(String somethingElse, int maxSpeed, String brand) {
       this.color = somethingElse;
       this.maxSpeed = maxSpeed;
       this.brand = brand;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public int getMaxSpeed() {
        return maxSpeed;
    }

    public void setMaxSpeed(int maxSpeed) {
        this.maxSpeed = maxSpeed;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

}

I've got this class right here and my question is do the parameters of the constructor have any connection with the properties of the class? Someone tried to convince me that the parameter of the constructor must have the same name as the property of the class. So I tried to change the name of the parameter from "color" to "somethingElse" and it seems to work... Why?

What I know is that the "this" keyword is used to make it clear to the compiler that with "this.color" I'm refering to the property "color" of the class. And with "= color" I'm assigning the constructor's parameter color to the object's property color. But what should I do now? Should I name the constructor's parameter to "color" instead of "somethingElse"? And does it make a difference?

I'm a beginner! I know professionals might think my question is "stupid".


Solution

  • No, the parameters dont have any connection with the properties of the class.

    But, does it make a difference? Well, yes and no. Let me explain:

    private String color;
    private int maxSpeed;
    private String brand;
    
    public Car(String somevar, int somevar2, String somevar3) {
        this.color = somevar;
        this.maxSpeed = somevar2;
        this.brand = somevar3;
    }
    

    Technically code this way doesn't make difference, it will works fine.

    But, imagine that someone - not you - created the Car class, and you will use it:

    weird IDE suggestions

    Reading the IDE suggestions, can you understood what each parameter means? Probably no.

    So, you don't need to use the same name of the fields in the parameters, but it will make your code be more readable and understandable.