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 Confusion on access modifiers 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 "Confusion on access modifiers" Watch "Confusion on access modifiers" New topic

Confusion on access modifiers

Amit K K Amit

Joined: Oct 10, 2011
Posts: 8

Need your help here. I am trying to understand why the following code is compiling and running when it should fail compilation.

What i have understand from the theory is, subclasses outside the package can't use a superclass reference to access a protected member then why my code is working here with the static decleration.
If i remove the static keword it fails compilation which is accepted. I am trying hard to understand why it is compiling when i am using the static with the variable decleration. Please help me here.

[Edit - added code tags - see UseCodeTags for details]
Helen Ma
Ranch Hand

Joined: Nov 01, 2011
Posts: 451
If the x is non-static, child class can only inherit it and use as if x is defined in its own class.
If the x is static, it is a variable that belongs to the class, not belong to any object instance. You can use it by Parent.x or obj.x.
If you are running it in Eclipse, by using obj.x, you will get a warning that static variable should be called in a static way, Parent.x

By the way, if you do this:

Polymorphism does not apply to static variable or methods. c is a parent type. c.x refers to the x in Parent.
Amit K K Amit

Joined: Oct 10, 2011
Posts: 8

Thanks Helen,
Thanks for helping me understand the concept.
I agree. Here's the link:
subject: Confusion on access modifiers
It's not a secret anymore!