• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Knute Snortum
  • Bear Bibeault
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Ganesh Patekar
Bartenders:
  • Frits Walraven
  • Carey Brown
  • Tim Holloway

static fields, methods - overwriting?

 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I thought that once a field was declared static, then there was only one copy of that field.  I thought the same went for methods.  I wanted to prove that to myself, and the results weren't what I expected:


Output:


I had thought that field 'a' would be re-set to 2 in class TrigClass, and that it would be 2, even when called from within class Class, if the call came after it was re-set to 2.  Also, I thought method swing() in class Class would be overwritten by the swing() in TrigClass, and there would be only one method (which would print "swing in TrigClass").  In main(), apparently, both fields (a in TrigClass and a in Class) and both methods (swing() in each class) exist independently.  If that's the case, what's the point of static?  What is unique about a field/method when they're declared static?
 
Ranch Hand
Posts: 125
1
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
static simply means belonging to a class, rather than to an object. So, static method in class A, belongs to class A. And you can call it, without needing an instance of class A. So, that's the point of having static members.
inheritance is a relationship between classes, where only non-static methods/fields participate; static methods/fields have no bearing on that.
 
Sheriff
Posts: 13517
223
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Static fields and methods get resolved to the declared type, not the actual runtime type because they dont participate in polymorphism. Read about static/early binding vs dynamic/late binding.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!