| Author |
protected variables
|
Sarikaa Bhatnagar
Greenhorn
Joined: May 10, 2005
Posts: 26
|
|
Hi, Can anyone pls tell why cant we access variable x when it is protected and pacakge is imported ? Parent.java ----------- package par; public class parent { protected int x = 9; } Child.java ---------- package other; import par.*; class child extends parent { public static void main(String args[]) { parent p = new parent(); system.out.print(p.x); } } Thanks, Sarika.
|
 |
Yogesh Baraskar
Ranch Hand
Joined: Oct 07, 2007
Posts: 33
|
|
since the child class is in different package, you cannot access protected variables using the instance of parent class. Protected variables can be accessible via subclass only. so create an object of child class and then you can access it.
|
 |
Sarikaa Bhatnagar
Greenhorn
Joined: May 10, 2005
Posts: 26
|
|
thanks, this is correct but wht i dont undersand is that why cant we access it with parent object because its a variable of parent only and child class has simply inherited it ? Sarika.
|
 |
Yogesh Baraskar
Ranch Hand
Joined: Oct 07, 2007
Posts: 33
|
|
because that is the property of protected variables. They can be access only via the subclass.
|
 |
Geetha Arthanari
Greenhorn
Joined: Nov 24, 2006
Posts: 25
|
|
|
For a subclass outside the package, the protected member can be accessed only through inheritance not by references.
|
 |
Manikandan Jayaraman
Ranch Hand
Joined: Sep 15, 2004
Posts: 225
|
|
Rule of Thumb: If 2 classes are in same package, "protected = public" whether the class extends the other class or not! If 2 classes are in different package, protected = private unless inherited. Also, if one extends the other "protected = private" when you try to access through reference. Automatically inheritted reference can be used.
|
Regards,<br />Mani<br />SCJP 1.4 (95%)<br />SCWCD 1.4 (94%)
|
 |
Sarikaa Bhatnagar
Greenhorn
Joined: May 10, 2005
Posts: 26
|
|
|
thanks a lot!!!
|
 |
 |
|
|
subject: protected variables
|
|
|