Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What is "non-static method" vs "static context" ?

 
achana chan
Ranch Hand
Posts: 277
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All.
Sometimes, when I try to add a simple method to exisitng codes, JAVA would give me this error :
non-static method compressedSize(int) cannot be referenced from a static context :
int cmpSize = compressedSize(cmpSize);
Can someone explain to me what this means please ?
TIA
 
Blake Minghelli
Ranch Hand
Posts: 331
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The concept of static is usually confusing for newbies, I know I was initially confused when I started to learn Java.
The simple answer is: That error will occur if a block of code in a static method attempts to access a non-static variable (e.g. instance member) or call a non-static method.
A brief explanation:
Static fields and methods are part of the generic class, i.e. part of the "template" that specific object instances are created from. Non-static fields/methods are associated to a specific instance, or object. So, static fields/methods have no way of accessing the members of a specific instance because they can't know which instance you are refering to.
Hope that helps!
 
Ron Newman
Ranch Hand
Posts: 1056
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
non-static == there is a "this" object
static == there isn't a "this" object
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic