vlio20
vlio20

Reputation: 9295

Java constructor with and without "this" before attributes

Maybe this question was asked here before, but I couldn't find it here.

It is basic question for Java developers, but here it goes: lets say I have class A with attribute a. What is the difference between these 2 constructors:

public abstract class A
{
   protected String a;

   public A()
   {
      a = "text";
   }
}

The second one:

public abstract class A
{
   protected String a;

   public A()
   {
      this.a = "text"; //Here is the same with this
   }
}

Upvotes: 1

Views: 2280

Answers (5)

om-nom-nom
om-nom-nom

Reputation: 62835

There is no difference at all, unless there is shadowing involved:

public abstract class A
{
   protected String a;

   public A(String a)
   {
      this.a = a; // assign external one to inner
   }
}

vs

public abstract class A
{
   protected String a;

   public A(String a)
   {
      a = a; // assign inner one to inner one
   }
}

Upvotes: 1

Ashish
Ashish

Reputation: 1941

There is no difference between the constructor this reference is used to automatically pass address of the caller object.

Upvotes: 0

BackSlash
BackSlash

Reputation: 22233

There is no difference in your specific case. But let's think about a constructor with an argument which has the same name as an attribute:

public abstract class A {
   protected String a;

   public A(String a) {
      this.a = a; 
   }
}

In that specific case, this.a is referring to the a attribute of class A, while a is referring to the local parameter

Upvotes: 1

Suresh Atta
Suresh Atta

Reputation: 121998

From docs and with your same example ,

The most common reason for using the this keyword is because a field is shadowed by a method or constructor parameter.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1499900

In the case you've given, there's no difference. Typically this is used to disambiguate between instance variables and local variables or parameters. For example:

public A(String a) {
    this.a = a; // Assign value from parameter to local variable
}

or

public void setFoo(int foo) {
    this.foo = foo;
}

Some people prefer to always use this.variableName to make it clearer to anyone reading the code; personally I find that if the class is well designed and the methods are short enough, it's usually clear enough already and the extra qualification just adds cruft. YMMV.

Upvotes: 6

Related Questions