0

If I create a class that looks like this:

public class TagManager {
private final Context mCtx;

public TagManager (Context ctx) {
    this.mCtx = ctx;
}

}

What is the difference between using

this.mCtx = ctx;

versus

mCtx = ctx;

As far as I can tell they both do the same thing but I can't find any discussion of it.

Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
easycheese
  • 5,859
  • 10
  • 53
  • 87
  • 1
    Check this http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html out. – Qw4z1 Sep 02 '12 at 15:22
  • Also see this http://stackoverflow.com/a/6547327/1166813 answer, since it is the same for variables and methods. – Qw4z1 Sep 02 '12 at 15:24

3 Answers3

4

For sure it's the same. It's just a matter of CodeStyle - it's up to you to select what you like more.

The only reasonable case to make this.* is when your argument and member variable have the same name. For example

    private final Context ctx;
    public TagManager (Context ctx) {
        this.ctx = ctx;
    }

However, Android Code Style tells us to use m*** prefix for member variables, so this situation should rare happen in your classes.

Good luck

Alex Coleman
  • 7,216
  • 1
  • 22
  • 31
AlexN
  • 2,544
  • 16
  • 13
2

Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called

public class Point {
    public int x = 0;
    public int y = 0;

    //constructor
    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

this.x on the example refer to public int x no int x

Aprian
  • 1,718
  • 1
  • 14
  • 24
1

Consider this:

public class foo {
private final int bla = 1;

public int blabla () {
    int bla = 2;
    return bla;//this will return 2
}

/

public class foo {
private final int bla = 1;

public int blabla () {
    int bla = 2;
    return this.bla;//this will return 1
}
Yellos
  • 1,657
  • 18
  • 33