简体   繁体   中英

'this' prefix in Java?

Does the this prefix for accessing member variables exist in Java?

Here is my HelloWorld code:

public class HelloWorld {

    public static int x = 0;

    public static void main(String[] args) {

        HelloWorld.x = 45;

        System.out.println(HelloWorld.x);
    }
}

The above code works with/without the class name prefixing the variable x . However, if i try: this.x = 45; or this->x = 45; I receive an error:

non-static variable this cannot be referenced from a static context

I understand member variables can be accessed without the HelloWorld (class name) prefix, like I have done. But, I want to know if the this prefix exists in Java, how do I use it?

EDIT:

Also, could you provide an example where this is appropriate?

duffymo & byte - I greatly appreciate your help. Thanks.

Java has this as a prefix, but it's a reference to the current instance.

Static methods and attributes are associated with a class, not an instance, so you can't use this inside a static method.

public class HelloWorld {

    public int x = 0; // note: now it's an instance attribute

    public static void main(String[] args) {

        HelloWorld hw = new HelloWorld();


        System.out.println(hw.x);
    }

    public int getX() { return this.x; }
    public void setX(int x) { this.x = x; }
}

You're attempting to use 'this' to refer to a static, not an instance variable. 'this' is only used to refer to the instance variables of an instantiated object of this class. You cannot use 'this' to refer to static variables on a class.

When you use 'this' you are saying "I want to refer to the variables of this particular instantiation of this class" . A static on the other hand is always going to be the same variable for the class, irrespective of instantiation.

In addition the correct syntax for referring to an instance variable is by the dot operator:

this.x = 42; //correct
this->x = 42; //will not compile as its not valid Java

So essentially what you're after is something like the following:

public class Foo {

    private int x;

    public void setX(int x) {
        this.x = x;
    }

    public int getX() {
        return this.x;
    }
}

public class HelloWorld {

    public static void main(String[] args)
    {
        Foo foo = new Foo();
        foo.setX(45);

        System.out.println(foo.getX());
    }

}

Remove the static modifier from your variable and then try it with this . Here is the difference:

Static variables exist only once in the whole program. No matter where you are, you could refer to HelloWorld.x and it would always be the same thing. That means, as you've declared it, anyone can modify it too, which may or may not be a good thing.

Member variables (not declared with static) are local to an instance of a class, which means you have to have created an instance with new before you can use it. However, every time you use new to create a new instance of that class, its non-static fields will be different. That is why you have to use this or, if in a different class, a reference to a specific instance in order to access them.

A clarification:

in getter methods it's not necessary to use the keyword this (as it's been shown in other answers). If you're new to Java this will introduce you to variable scopes (local variables vs instance variables). In other words the following works perfectly:

public class Foo {
    private int x;

    public void setX(int x) {
        this.x = x; //Here the keywork this is necessary!
    }

    public int getX() {
         return x; //in this case the 'x' can only be instance variable 
    }
}

There is also another important use of this for invoking constructors defined in the same class (You might want to check the keyword 'super' as well). Check the following:

public class HelloWorld {
    public static void main(String[] args) {

        Foo foo1 = new Foo();
        Foo foo2 = new Foo(3, 4, 5);

        System.out.println("Foo1:\n" + foo1);
        System.out.println("Foo2:\n" + foo2);
    }
}

class Foo {
    private int x, y, z;

    public Foo() {
        this(-1, -1);
    }

    public Foo(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public Foo(int x, int y, int z) {
        this(x, y);
        this.z = z;
    }

    @Override
    public String toString() {
        return "x= " + x + "\ny= " + y + "\nz= " + z + "\n";
    }
}

Enjoy!

You can only use "this" from within an object instance.

"static", by definition, is OUTSIDE of ANY object.

Here's an excellent link in the Java documentation:

http://download.oracle.com/javase/tutorial/java/javaOO/classvars.html

'Hope that helps!

for static variables, use ClassName (like you did). For instance (non-static) variables, use this.variableName

you can use it to access instance variables and methods, you are getting this error because you are using this to access static variables.

and also ... java doesn't have => , in java you use the .

  objectName.variableName = newValue

Use this for getters/setters/constructors.

For example.

class Test {

int x;
int y;

public void Test(int x, int y) {
  this.x=x;
  this.y=y;
}

public void setX(int x) {
  this.x=x;
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM