Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why can't the 'this' keyword be used here?

Tags:

java

oop

this

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
    }
}
like image 475
tubby Avatar asked Oct 19 '25 00:10

tubby


1 Answers

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.

like image 147
akhil_mittal Avatar answered Oct 20 '25 14:10

akhil_mittal