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 Protected Member Access Problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Protected Member Access Problem" Watch "Protected Member Access Problem" New topic

Protected Member Access Problem

Soumya Ranjan Mohanty
Ranch Hand

Joined: Mar 07, 2010
Posts: 44
I have two classes as


Still i am getting Compilation error as x has protected access in p.Animal .. But Protected Members can be accessed From Subclasses Outside the Package, Then y i am geeting such error?
Abimaran Kugathasan
Ranch Hand

Joined: Nov 04, 2009
Posts: 2066

protected members can accessed only through inheritance if the sub class is in another package.

Noe try it.

|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|
Sahil Kapoor
Ranch Hand

Joined: Sep 12, 2009
Posts: 316

NOTE: You can use Animal reference to access protected member within package p, but not outside package p.
if you want to access x then just use x to access it or this.x. But mind it, static context cannot have reference to any non-static context. Thats
why in the above code (by Abimaran ) x is accessed through Dog object. The following code is also legitimate and in this code we would use just

The above code just compiles well ,But in order to print the value of x, you have to define main(String[] args) method which would call main() method above
by the use of some instance of Dog class.

One more Tip : We can have main() method, this is an overloaded method and you would study it in later chapters.

NOTE: After grasping the above concept, try answering the following question, but before attempting it do not forget to read the rules given as a link in the same.


SCJP 6.0 96%

(Connecting the Dots ....)
Shanky Sohar
Ranch Hand

Joined: Mar 17, 2010
Posts: 1051

read this post everything will be cleared..........

SCJP6.0,My blog Ranchers from Delhi
I agree. Here's the link:
subject: Protected Member Access Problem
It's not a secret anymore!