0

I'm a beginner in Java programming and I'm having some problems to understand some concepts. I would like to know if both implementations are the same:

Code 1

public class MyThisTest {
  private int a;

  public MyThisTest(int a) {
    this.a = a;
  }

Code 2

public class MyThisTest {
  private int a;

  public MyThisTest(int b) {
    a = b;
  }
user804406
  • 73
  • 5

3 Answers3

2

Yes, both are the same, let's see why:

First

public class MyThisTest {
  private int a;

  public MyThisTest(int a) {
    this.a = a;
  }

You are using this to refer the member variable a. The use of this is because by parameter there is another a variable. If you don't use this what variable will be assigned the value? The same as the parameter, so it doesn't take effect because it is 'auto-assign' the value.

Word this ensures tthe member variable is referenced. This is mostly used in constructors and getter/setters because the parameter name should be the same as the member variable name, so to handle the ambiguity this is used.

The second code

public class MyThisTest {
  private int a;

  public MyThisTest(int b) {
    a = b;
  }

Into constructor there is no ambiguity between variables, so this is not needed, but you can still use this and it works perfectly.

swpalmer
  • 3,890
  • 2
  • 23
  • 31
J.F.
  • 13,927
  • 9
  • 27
  • 65
1

Yes both implementations are same. But I would highly recommend you to read about it in detail so that you don't make any future mistake. This answer goes in detail about when we should use this.

Zain Arshad
  • 1,885
  • 1
  • 11
  • 26
1

this keyword would be added by compiler. Actually, if you write something like this

public class A {

    private int a;

    public A(int b) {
        a = b;
    }
}

Compile and then decompile it you can see the work of compiler

 //
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//


public class A {
    private int a;

    public A(int b) {
        this.a = b;
    }
}

So, i would say avoiding this is just a usage of some syntax sugar.