public class example {
int a = 0;
public void m() {
int b = this.a;
}
public static void main(String[] args) {
int c = this.a;
}
}
I am new in java. Why I cannot use “this” in the main method?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
thisrefers to the current object. However, themainmethod is static, which means that it is attached to the class, not to an object instance, hence there is no current object insidemain().In order to use
this, you need to create an instance of your class (actually, in this example, you do not usethissince you have a separate object reference. But you could usethisinside yourm()method, for example, becausem()is an instance method which lives in the context of an object):By the way: You should get familiar with the Java naming conventions – Class names usually start with a capital letter.