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

11

50
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?

Bul answered 26/7, 2012 at 7:36 Comment(1)
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.Mckibben
S
100

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;
    }
}
Sac answered 26/7, 2012 at 7:41 Comment(4)
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?Smacking
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.Sac
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.Noncompliance
@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.Sac
T
7

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

Tattle answered 26/7, 2012 at 7:40 Comment(0)
L
7

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.

Lout answered 1/6, 2015 at 6:21 Comment(1)
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".Trisect
H
3

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

Hinojosa answered 26/7, 2012 at 7:40 Comment(0)
S
2

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.

Subclimax answered 26/7, 2012 at 7:39 Comment(2)
would you care to explain what's the problem of my answer, or of @Peter's answer?Subclimax
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 ^^)Sac
B
1

"this" keyword is only applicable where an instance of an object is created. And in static method no instance is created because static method belongs to class area.

Barometer answered 8/3, 2016 at 6:34 Comment(0)
C
1

There is no problem with static methods setting values for static fields.

The only issue is usage of this keyword. Please note that since static methods are processed at the time of class loading, it's all but certain that no "this" exists at the point of time, which is why its only logical the usage of this keyword isn't allowed in a static context.

On the other hand, static method can be invoked from an object because it is made accessible to the object. The intention behind static data members and behaviours is to make it common to all the instances of that class.

Carrycarryall answered 16/4, 2021 at 3:25 Comment(0)
H
0

Keyword "this" refers to the object that you are operation with. In your case this inside any non-static methods or constructor (if you have one and and if you use "this" inside that), then "this" refers to that particular instance of the class Sub.So it is applicable only when the object is created. But anything in the static context of a class, you can use without even creating object for that as it is resolved during the class loading. "this" resolved only when object is created ( you can even say dynamically for which object). So "this" make sense in static context. Hope it helps. God bless.

Hammers answered 26/7, 2012 at 8:10 Comment(0)
M
0

when we declare variable and method is static then this is share by among object where this keyword only pointing to current object. suppose you have created five object of class foo then only one copy of made of (int y) shred by all object.so if you access int y using this keyword then compiler get a ambiguity which object have to point because static int y is shared by all object . you have access static variable using class name.

Monaco answered 19/5, 2018 at 17:15 Comment(0)
Z
0

Let's Understand by a Simple Example

Example 1

public class Sample{
   static int num = 50;
   public static void demo(){
      System.out.println("Contents of the static method");
   }
   public static void main(String args[]){
      Sample.demo();
   }
}

Output

Contents of the static method

Example 2

public class Sample{
   static int num = 50;
   public static void demo(){
      System.out.println("Contents of the static method"+this.num);
   }
   public static void main(String args[]){
      Sample.demo();
   }
}

Output

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

Summary Observe Example 2 wisely , you will get to know that you will get CTE. These both examples will help you understand the difference

Keep Learning , Keep Growing

Zalucki answered 24/9, 2023 at 12:41 Comment(0)
B
0

'this' keyword is used to store address /reference of object. For static method only one time memory is allocated, but in case of non static memory allocated each time when object is created each object has different address. So to access each object uniquely we need address and this keyword help us to do so. For static method only one copy is present, means only one reference, we can access static member without object reference.

Busse answered 31/10, 2023 at 3:21 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Dolmen

© 2022 - 2025 — McMap. All rights reserved.