| Author |
protected access level
|
Jacky Zhang
Greenhorn
Joined: Sep 17, 2006
Posts: 18
|
|
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
Joined: Feb 20, 2006
Posts: 132
|
|
|
Sounds ok.
|
 |
Sarada Bikkina
Greenhorn
Joined: Jan 30, 2006
Posts: 9
|
|
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
|
Thanks N Regards,<br /> Sarada Bikkina
|
 |
Tom Johnson
Ranch Hand
Joined: May 11, 2005
Posts: 142
|
|
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 ]
|
<a href="http://faq.javaranch.com/java/UseCodeTags" target="_blank" rel="nofollow">Use Code Tags!!</a>
|
 |
David Kennedy
Ranch Hand
Joined: Jan 22, 2006
Posts: 33
|
|
Or you could just do:
|
"There are only 10 types of people in the world: Those who understand binary, and those who don't"
|
 |
Sarada Bikkina
Greenhorn
Joined: Jan 30, 2006
Posts: 9
|
|
|
Thanks a lot.I understood the concept now.
|
 |
 |
|
|
subject: protected access level
|
|
|