aspose file tools
The moose likes Java in General and the fly likes static methods accessing instance variables. Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "static methods accessing instance variables." Watch "static methods accessing instance variables." New topic
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.
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: static methods accessing instance variables.
 
Similar Threads
Help with compiler speak
whether private static variable can be accessed out side the class
class types
Access to static variable
method overriding