• Post Reply Bookmark Topic Watch Topic
  • New Topic

static main calling non-static methods  RSS feed

 
Ashwin Rao
Ranch Hand
Posts: 89
C++ Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


This is a program from Head First Java!
My question is..since main is static it shouldn't be able to call non-static methods because statics do not use any instance variable values but in the above program we're call a non-static method go() how is it possible?
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because it's invoked on the object "gui". What wouldn't work is to call "SimpleGUI1B.go()" - because it's not a static method.
 
Campbell Ritchie
Marshal
Posts: 56525
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
…and welcome to the Ranch
 
Paul Clapham
Sheriff
Posts: 22819
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's another example:



I expect if you saw this code you wouldn't think of pointing out that "substring()" isn't a static method of the String class, and asking why it was allowed. I expect you would find it a perfectly natural piece of code. Am I right?
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!