| Author |
Doubts on Protected Members
|
jammy ponkia
Greenhorn
Joined: Mar 23, 2008
Posts: 15
|
|
Hi All, I have a class pack in a package packed as follows package packed; public class pack { static public int x1 = 7; static protected int x2 = 8; static int x3=9; static private int x4 =10; } An other class Test in a different package import packed.pack; class test extends pack { public static void main( String args[] ) { pack p = new pack(); System.out.println( pack.x2 ); } } If i remove static from protected variable x2, i am getting a compiler error that x2 is not visible.Why is it so? As per the API, i should be able to access the protected variables in or outside the package using inheritance.
|
 |
Ravikanth kolli
Ranch Hand
Joined: Feb 10, 2008
Posts: 179
|
|
hi jammy, you are now accessing the variable in a static way so if you remove static it is going to give a compile error. So if you need to access x2 then using the instance p should help. It is going to be something like p.x2 Hope this explains the question
|
-kolli
|
 |
Nevin kumar
Ranch Hand
Joined: Mar 15, 2008
Posts: 93
|
|
hi, If you remove static modifier to variable x2 then it becomes a instance member,you cannot access a instance member using a class name.In that case you can access x2 using reference p as long as x2 is static only.Because you can access protected members in a different package only through inheritance but you cannot access them by creating a reference to that class.In that case you can access only static members but you cannot access instance members by using references. [ March 23, 2008: Message edited by: Naveen kumar ]
|
 |
 |
|
|
subject: Doubts on Protected Members
|
|
|