| Author |
referencing to static from non-static context
|
jan ter avest
Ranch Hand
Joined: Dec 18, 2006
Posts: 46
|
|
Hi, below the code excerpt that confuses me, its from the Whizlabs simulator. It compiles fine but I can't understand why it's allowed to call static method get1 from non-static method get(). How come this doesn't result in a compiler error?? class Parent { static void get1(){ System.out.print("Parent get1 "); } void get2() { System.out.print("Parent get2 ") ; } public void get() { get1(); // calling static meth from non-stat context?? get2(); } }
|
SCJP1.5 SCWCD1.5
|
 |
Keith Lynn
Ranch Hand
Joined: Feb 07, 2005
Posts: 2341
|
|
|
The static methods belong to the class, and so essentially the call to the static method would look like this.get1() which is equivalent to Parent.get1(). All instances can see the static variables, but no static method can directly access the instance variables or methods.
|
 |
Pankaja Shinde
Ranch Hand
Joined: Sep 15, 2006
Posts: 61
|
|
In simple words. You can call static members from non-static context, but you can't call non-staic members from static context, using simple names. By using class name or class objects, you can call non-staic members from static context.
|
 |
ShivKumar Rajawat
Greenhorn
Joined: Mar 13, 2007
Posts: 17
|
|
What pankaja said is right. But the sentense given below needs a small correction. "By using class name or class objects, you can call non-staic members from static context" In Fact only class name can not be used for non static members. you need an instance of the class to call nonstatic members. So if you want to call some nonstatic method from a static context you shall use an object reference of the class. In multithraded situations it's bettr that you do not try such things. for more details on this multithrading issues you can refer to Kathy & Berts Book.
|
Regards<br />-Shiv
|
 |
 |
|
|
subject: referencing to static from non-static context
|
|
|