• 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

static context

 
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi, there
i know we can't invoke nonstatic method in static context, it is obvious that line2 is not legal. However, i don't understand why we can invoke non-static mehond inside main()which is also static method(line 1). could anyone help?
thanks in adv...
public class chenwei{
chenwei(){
System.out.println("how are you");
}
static void chen(){

//this.wei();//2
}
public void wei(){
int b=23;
System.out.println("i got you");
}

public static void main(String args[]){
chenwei baby=new chenwei();
baby.chen();//1
}

}
 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You're quite right. You CAN'T invoke a non-static method from the static main() method. However, in your example you create an instance of class Chenwei before invoking a method on that instance. This is OK. If you attempted to call the non-static method directly from main() you would get a compiler error.
public class Chenwei{
public static void chen(){
System.out.println("static");
}
public void wei(){
System.out.println("non static");
}
public static void main(String args[]){
chenwei baby=new chenwei();
baby.chen(); // OK
baby.wei(); // OK
chen(); //OK
wei(); // Compiler error! Static reference to non-static method
}
}
Hope that makes sense!
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic