File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

Doubt about static member variables

Timothy Sam
Ranch Hand

Joined: Sep 18, 2005
Posts: 751
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
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2398
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: 1710
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,

I agree. Here's the link:
subject: Doubt about static member variables
It's not a secret anymore!