| Author |
static methods accessing instance variables.
|
poorvika chanda
Greenhorn
Joined: Oct 31, 2011
Posts: 13
|
|
today going through some java topics like static methods cannot access instance methods and variables.And another topic which says the this reference can be used to explicitly invoke other methods in class. so I wrote a small programm in which static method accesses instance variables indirectly.I wrote a static method names methodA with parameter as the refernce variable of type Test_This(containing class)and instance method methodB.in method B I created the object of type Test_This and passed the this reference of object to methodB.As a result b can access the instance fields and methods of the this object.
Please correct me if I am wrong
public class Test_This {
private int a;
private int b;
Test_This(){
a = 100;
b = 200;
}
public static void methodA(Test_This obj){
obj.toString();
System.out.println("a is"+obj.a);
System.out.println("b is"+obj.b);
}
public void methodB(){
methodA(this);
}
public static void main(String[] args) {
Test_This tt = new Test_This();
tt.methodB();
}
}
|
 |
John Jai
Bartender
Joined: May 31, 2011
Posts: 1776
|
|
|
The this you pass as a argument refers to the reference of the current object. It's like passing any other reference to a method. The only thing is that you cannot use this inside a static context.
|
 |
 |
|
|
subject: static methods accessing instance variables.
|
|
|