java - How do I refer to a variable from a method in the same class -
java - How do I refer to a variable from a method in the same class -
i surprisingly find confusing. must missing something.
so have simple syntax
public class omg{ public static void main(string args[]){ int hi=2; letsdoit(); system.out.println(hi); } public static void letsdoit(){ hi+=1; } }
obviously cause error, since hi local variable.
judging experience python added this
public class omg{ public static void main(string args[]){ int hi=2; letsdoit(); system.out.println(hi); } public static void letsdoit(){ this.hi+=1; } }
which adds error when non-static variable cannot accessed static method.
i added static
hi
public class omg{ public static void main(string args[]){ static int hi=2; letsdoit(); system.out.println(hi); } public static void letsdoit(){ this.hi+=1; } }
the compiler scolds me illegal expression. substitute static private
(which answers, recommend) same error.
where's mistake? there way can solve this, without making global class?
you cannot declare static
variables within method because static
modifier means method or field belongs class.
the easiest solution problem declare variable static
class variable. using approach, need remove this
this.hi
in lestdoit
method. code this:
public class omg { static int hi=2; public static void main(string args[]) { letsdoit(); system.out.println(hi); } public static void letsdoit() { hi+=1; } }
another solution may using non static
variable hi
. need remove static
modifier letsdoit
method access hi
field, because static
methods cannot access instance fields because, explained above, static
means method or field belongs class , not specific object instance of class.
the solution be:
public class omg { int hi=2; public static void main(string args[]) { //note have create new instance of omg //because, again, static methods cannot access non-static methods/fields omg omg = new omg(); omg.letsdoit(); system.out.println(omg.hi); } public void letsdoit() { this.hi+=1; } }
more info:
java tutorials. using keyword java tutorials. understanding class members java class scope
Comments
Post a Comment