*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes protected variables Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "protected variables" Watch "protected variables" New topic
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: 230
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!!!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: protected variables
 
Similar Threads
doubt in access modifier. Please explain this code
Access protected member from the class of different package.
access level
Problem about protected attribute
Rules for Protected and Default Members