Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

protected access level

 
Jacky Zhang
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A protected member may be accessed by a subclass even if the subclass is in a different package.

If the subclass is in the same package, the protected member can be accessed as though it were public through super().

If the subclass is in a different package, the protected member can be accessed only through inheritance.

Are my preceding statements correct?
 
Petrus Pelser
Ranch Hand
Posts: 132
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sounds ok.
 
Sarada Bikkina
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,I have been just working to check the access level of the protected modifier by creating two classes in two different packages.Here are the two classes

In package firsttry
public class TryProtected {
protected int n = 10;
public static void main(String args[])
{
TryProtected t = new TryProtected();
}
}

In package Sample
package Sample;
import firsttry.TryProtected;
public class Test extends TryProtected{
public static void main(String args[])
{
TryProtected t = new TryProtected();
System.out.println("the value is**:"+t.n);
}
}
here in the above class Test,when i try to access the protected variable n from TryProtected class im getting a compile time error.
can any one please tell me whats the problem in these programs?

thanks in advance
 
Tom Johnson
Ranch Hand
Posts: 142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First of all - please use the [C0DE] [/C0DE] tags as I have done below to preserve the indentation as its far easier to debug.

Anyway,
The answer to your question is in the original question :

If the subclass is in a different package, the protected member can be accessed only through inheritance."

Your class Test is in a different package than TryProtected so you cannot access the variable "n" of class TryProtected from any method of class Test USING THE "." OPERATOR as you have tried with


As the original post said, you could have access it USING INHERITANCE
like this (note we cannot access an instance variable from a static method such as "main" so I have added another method to Test.java)


Hope this explains the difference between direct "." access and inheritance access

Cheers
Tom
[ September 20, 2006: Message edited by: Barry Gaunt ]
 
David Kennedy
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or you could just do:

 
Sarada Bikkina
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot.I understood the concept now.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic