Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Protected Member Access Problem

 
Soumya Ranjan Mohanty
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have two classes as



and



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
Posts: 2066
Clojure IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
protected members can accessed only through inheritance if the sub class is in another package.


Noe try it.
 
Sahil Kapoor
Ranch Hand
Posts: 316
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



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
x.





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 QUESTION OF THE DAY SERIES
 
Shanky Sohar
Ranch Hand
Posts: 1051
Eclipse IDE Firefox Browser
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
read this post everything will be cleared..........

http://www.coderanch.com/t/502346/java-programmer-SCJP/certification/protected-variable
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic