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?
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.
You must create an instance of example
example e = new example()
e.m()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With