• 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
  • Paul Clapham
  • Tim Cooke
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Frank Carver
  • Henry Wong
  • Ron McLeod
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Himai Minh

Doubt about static member variables

 
Ranch Hand
Posts: 751
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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: 2412
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Run away! Run away! Here, take this tiny ad with you:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic