3

I understand that this refers to the current object. So instead of using objectname.fun(objectname.nonstaticmember) , why can't I use objectname.fun(this.nonstaticmember)

Please refer example below, and see the last two comments at the end.

public class Question
{
    int data;

    void myfun(int data)
    {
        System.out.println("data=="+data);
    }

    public Question(int data)
    {
        this.data = data;
        // TODO Auto-generated constructor stub
    }

    public static void main(String[] args)
    {   
        Question question = new Question(10);
        //question.myfun(question.data);//WORKS
        question.myfun(this.data);//DOES NOT WORK
    }
}
tubby
  • 2,074
  • 3
  • 33
  • 55

3 Answers3

5

As you mentioned this keyword is used to refer to current object and not to the class as such. In your case you are trying to use it(this) in a static method main. Also check this link.

Community
  • 1
  • 1
akhil_mittal
  • 23,309
  • 7
  • 96
  • 95
  • Ohh, so 'this' inside a function refers to the object which was used to call that function? So since no objects were used to call main(being static), so it would give me 'Cannot use this in a static context'. Thanks, wasn't aware – tubby Oct 19 '15 at 03:55
  • 1
    @PepperBoy: In simplest terms `this` refers to current instance and `static` keyword always point to something that belongs to the whole class and not to a specific instance. So `this` has no meaning for static methods. – akhil_mittal Oct 19 '15 at 03:57
3

main() is a static method (class method) it does not run from an object. Since it's in the class-context the keyword this has no meaning (it has no object to refer to).

Community
  • 1
  • 1
Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
1

In java this keyword use to refer current object but main is a static method, inside static method this keyword have no meaning.

public class Line {
public static void main(String[] args){
    System.out.println(this);

} }

Output: compile time error "non-static variable this cannot be referenced from a static context".