Home > Enterprise >  Is there any difference between using the THIS keyword and assigning the parameter to a field?
Is there any difference between using the THIS keyword and assigning the parameter to a field?

Time:10-18

Can anyone please explain the difference between using the this keyword or assigning the parameterised constructor value ('cartype') to a relevant field('make'). See code and two options below '**': We are assuming an object has been instantiated with an argument ...

public class Car {

    String make ;


    Car(String cartype) {

        make = cartype; // **
        this.make = cartype; // **
    }
}

CodePudding user response:

In your example there is no meaningful difference.

The explicit reference would be required if the constructor argument had the same name. For example:

String cartype;

Car(String cartype) {
    this.cartype = cartype;
}

Because otherwise cartype = cartype; would just set the variable to itself and nothing would set a value to the class field.

Sometimes this. makes it clear to the compiler when otherwise there would be ambiguity. Probably more important is when it makes it clear to the programmer when otherwise there could be ambiguity. In cases like your example it's really just a matter of preference/convention.

CodePudding user response:

the "this.make" is the explicit way of saying the same "make" property. Now, you don't generally need to type the extra "this." inside any method of class , unless there is an ambiguity , like when there is also a local variable with the exact same name.

In that case to make it clear to java compiler that which one (the local variable or instance variable) you are referring to, you will use the "this." prefix to make it clear I'm talking about instance variable with that name

a typical case where you have to use it is in constructor like below:

Car(String make) {
   this.make = make;
}

you are saying take the local variable "make" and put its value into instance variable "make".

  • Related