• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

referencing to static from non-static context

 
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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();
}
}
 
Ranch Hand
Posts: 2412
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic