This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubt about static member variables Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Doubt about static member variables" Watch "Doubt about static member variables" New topic
Author

Doubt about static member variables

Timothy Sam
Ranch Hand

Joined: Sep 18, 2005
Posts: 746
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!


SCJP 1.5
http://devpinoy.org/blogs/lamia/ - http://everypesocounts.com/
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
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.
Chandra Bhatt
Ranch Hand

Joined: Feb 28, 2007
Posts: 1707
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


cmbhatt
 
GeeCON Prague 2014
 
subject: Doubt about static member variables