Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why cannot use "this" in the main method?

Tags:

java

   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?

like image 746
joy Avatar asked Dec 04 '22 01:12

joy


2 Answers

this refers to the current object. However, the main method is static, which means that it is attached to the class, not to an object instance, hence there is no current object inside main().

In order to use this, you need to create an instance of your class (actually, in this example, you do not use this since you have a separate object reference. But you could use this inside your m() method, for example, because m() is an instance method which lives in the context of an object):

public static void main(String[] args){
    example e = new example();
    int c=e.a;
}

By the way: You should get familiar with the Java naming conventions - Class names usually start with a capital letter.

like image 112
Andreas Fester Avatar answered Dec 05 '22 15:12

Andreas Fester


You must create an instance of example

example e = new example()
e.m()
like image 24
ollins Avatar answered Dec 05 '22 14:12

ollins