aspose file tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes referencing to static from non-static context 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 » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "referencing to static from non-static context" Watch "referencing to static from non-static context" New topic
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: referencing to static from non-static context
 
Similar Threads
Statics
Static methods and inheritance.
OO, method calls in compile time
Another hiding vs overriding question
Static methods