File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Confusion on access modifiers Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Professional Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "Confusion on access modifiers" Watch "Confusion on access modifiers" New topic
Author

Confusion on access modifiers

Amit K K Amit
Greenhorn

Joined: Oct 10, 2011
Posts: 8

Guys,
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: 319
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
Greenhorn

Joined: Oct 10, 2011
Posts: 8

Thanks Helen,
Thanks for helping me understand the concept.
 
 
subject: Confusion on access modifiers
 
Threads others viewed
Protected - access modifier
default members
about protected n static
Access Modifiers
problem on extending a class declared on the same package!!
developer file tools

cast iron skillet 49er

more from paul wheaton's glorious empire of web junk: cast iron skillet diatomaceous earth rocket mass heater sepp holzer raised garden beds raising chickens lawn care CFL flea control missoula heat permaculture