Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

doubt in protected access specifier

 
wali nagesh
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
how is protected access specifier used in a subclass outside a package?
how about using parent class reference in a child class to access protected variable?
 
Punit Singh
Ranch Hand
Posts: 952
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
wali nagesh wrote:how is protected access specifier used in a subclass outside a package?
how about using parent class reference in a child class to access protected variable?


Protected is only inherited by subclasses, so you can only use protected member using subclass reference outside a package.

Remember one thing leaving public access modifier, anything outside a package is considered as private, so you cannot call anything without public modifier using superclass references.

Do you need examples or you are clear now?
 
Ken Truitt
Ranch Hand
Posts: 124
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The access modifiers proceed from least restrictive to most restrictive thus:

public protected [default] private

As has been said, protected class members are inherited by subclasses even outside of the package
in which they are defined.

But subclasses outside of the package can only use these members via inheritance--and NOT by
reference--not by using an instance of the class they are defined in:

//pseudo code

package A; class A1 { protect int x = 7; ... }

package B; class B1 extends A1 { A1 myA = new A1(); void myMeth() { System.out.println(x); } // prints 7

//NOT ----------------> void myMeth() { System.out.println(myA.x); }
//end pseudo code

It's an important distinction that you may be tested on.





 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic