+ 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); } }
5 odpowiedzi
+ 4
While I wouldn't code it this way, I believe this gives you what you asked for.
https://code.sololearn.com/ca0DFhyMveiz
+ 3
No, static methods must be called by the class name. Instances like obj can only be used to access instance based methods.
+ 2
Thanks a lot,your code helped a lot.
+ 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.
+ 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);
}
}