• 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

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

 
Ranch Hand
Posts: 277
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 331
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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!
 
Ranch Hand
Posts: 1056
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
non-static == there is a "this" object
static == there isn't a "this" object
 
permaculture is giving a gift to your future self. After reading this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic