Why can't we use 'this' keyword in a static method

88,987

Solution 1

Because this refers to the object instance. There is no object instance in a call of a static method. But of course you can access your static field (only the static ones!). Just use

class Sub {
    static int y;
    public static void foo() {
         y = 10;
    }
}

If you want to make sure you get the static field y and not some local variable with the same name, use the class name to specify:

class Sub {
    static int y;
    public static void foo(int y) {
         Sub.y = y;
    }
}

Solution 2

The main reason why we can not use "this" in static method context:-

this :- "this" means current class OBJECT , so its clear that "this" only come in the picture once we intended to create an Object of that class.

static method:- there is no need to create an object in order to use static method. means "instance" or object creation doesn't any sense with "static" as per Java rule.

So There would be contradiction,if we use both together(static and this) . That is the reason we can not use "this" in static method.

Solution 3

this is referring to this instance of the object Sub. As the method is static, there is not an instance of Sub.

Solution 4

To make your code work write it like this:

class Sub {
    static int y;
    public static void foo() {
         Sub.y = 10;
    }
}

You can set static fields in static methods, but you don't have access to this in static method because this represents the current instance of the object, and in a static method you have no instance.

Solution 5

This means "this" object but there isn't one. In your case you can use the class name as @tibtof suggests.

Share:
88,987

Related videos on Youtube

Pradeep Vairamani
Author by

Pradeep Vairamani

Part time superhero

Updated on July 09, 2022

Comments

  • Pradeep Vairamani
    Pradeep Vairamani almost 2 years
    class Sub {
        static int y;
        public static void foo() {
             this.y = 10;
        }
    }
    

    I understand that this represents the object invoking the method and that static methods are not bound to any object. But in the above mentioned case, the variable y is also static.

    If we can invoke static method on class object, why can't we allow static methods to set the static variables of the class.

    What is the purpose of this additional constraint?

    • Mark McKenna
      Mark McKenna over 7 years
      I realize this is an ancient question but I want to +1 it as a pretty valid point. Although for fields the answer is simple (leave the qualifier out), for static inner classes it becomes relevant, and is also relevant when what you want is a reference to the runtime instance of the class itself. For example I can type 'MyClass.class' to get the singleton Class<MyClass>, but just 'class' by itself is invalid and there's no similar workaround. This leads to the class name potentially being repeated through the unit which is not very DRY.
  • tibtof
    tibtof almost 12 years
    would you care to explain what's the problem of my answer, or of @Peter's answer?
  • brimborium
    brimborium almost 12 years
    There is nothing wrong with your answer. Upvoted it to 0 again. (which leaves you with +8 rep overall because of the crappy voting-rep system ^^)
  • xehpuk
    xehpuk over 8 years
    The downvoters may have thought that this doesn't really answer the question, because you basically repeated what the OP has already known and only provided a verbose workaround. If the class is named ThisClassHasAQuiteLongName, wouldn't it be nicer to refer the class as this in static methods?
  • brimborium
    brimborium over 8 years
    That's not really true though, I have provide an explanation for why this can't be used in static methods (because there is no instance of the class to be named this) and showed two ways of accessing the fields. Being able to use this in a static context as a replacement of the class name would be missleading and inconsistent (at least imho). Thanks for your feedback though, that might as well have been the reason for the downvotes.
  • Diogenes Creosote
    Diogenes Creosote over 7 years
    The question, as I understood it and which I also want to know, is why Java does not overload the meaning of this in a static context to mean the class, So instead of Sub.y one could type this.y. It would seem like an obvious design choice, because it eliminates the need to explicitly mention the class name, which could change. In general, when someone asks "why is x defined to be y but not also z in a different context" it is not satisfactory, and indeed kinda toxic and condescending to reply "because it's defined to be y." It made me feel dumb for wondering the same, as I still am.
  • brimborium
    brimborium over 7 years
    @AndrewCone thanks for the feedback. You are making a very good point (on why I got downvoted). And on the topic: I think the reason is Java's focus on having (or at least trying to have) a clean object oriented structure. When you overload a keyword, readability suffers. With the current definition, when you read this.y, you know, it's a local variable and not a static variable. So it is cleaner.
  • Ram
    Ram almost 6 years
    You just mentioned that there is a Java rule for not to use class instance to call upon static fields. There is no such Java rule(s) rather it has some specific reason "the static fields/ methods get created and stored in the memory area called PermGen at compile time only. The static things are part of class only so we can access them with class name directly, no need to create instance to access them".