+ 1

accessing instance variable from static method

how can i modify this code to access instance variable from static method class A { int x; static void show( int x) { this.x=x; } } public class B { public static void main(String[] args) { A obj=new A(); obj.show(10); } }

14th Jun 2018, 11:05 PM
harshit
harshit - avatar
5 Antworten
+ 4
While I wouldn't code it this way, I believe this gives you what you asked for. https://code.sololearn.com/ca0DFhyMveiz
14th Jun 2018, 11:55 PM
John Wells
John Wells - avatar
+ 3
No, static methods must be called by the class name. Instances like obj can only be used to access instance based methods.
17th Jun 2018, 12:57 AM
John Wells
John Wells - avatar
+ 2
Thanks a lot,your code helped a lot.
15th Jun 2018, 12:07 AM
harshit
harshit - avatar
+ 1
By making the show method public? It would be easier if you use the code playground and link the program. Us testing it helps us solve it faster too, and who knows, we may even learn a thing or two.
14th Jun 2018, 11:30 PM
Andre Daniel
Andre Daniel - avatar
+ 1
In this code can we write obj.show(obj, 10); instead of A.show(obj,10); ? class A { int x; static void show(A self, int x) { self.x=x; } } public class B { public static void main(String[] args) { A obj=new A(); A.show(obj, 10); System.out.println(obj.x); } }
17th Jun 2018, 12:19 AM
harshit
harshit - avatar