Win a copy of Learning OpenStack Networking: Build a solid foundation in virtual networking technologies for OpenStack-based clouds this week in the Cloud/Virtualization forum!
  • 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:
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Knute Snortum
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Ganesh Patekar
  • Stephan van Hulst
  • Pete Letkeman
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Ron McLeod
  • Vijitha Kumara

Doubt about static member variables  RSS feed

 
Ranch Hand
Posts: 751
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys! I have doubts wether static member variables are inherited. I tried the following...




it would seem like myX from class A is still accessible from class B through inheritance. Could you guys please explain to me what's happening here? Thanks!
 
Ranch Hand
Posts: 2410
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is from the Java Language Specification 8.3.

A class inherits from its direct superclass and direct superinterfaces all the
non-private fields of the superclass and superinterfaces that are both accessible to
code in the class and not hidden by a declaration in the class.
 
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Sam,



Your code wont compile, if you place both the classes in the same file. Because there can be one and only public class per source file.

Anyways if you remove public from the class A, the description would be as following:

Until you declare static member as private, it is accessible by the subclasses. There is only one copy of the myX so if the subclass method increments myX it increments the class variable myX.
If the class is public and member variable is also public and static as well in your case, it is accessible by the world, even you dont require the instance of the class to access the static member variable.

I think your confusion runs around polymorphic behavior, which can not be achieved if method of the super class is static. No run time polymorphism.

Thanks and Regards,
cmbhatt
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!