File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

protected variables

 
Sarikaa Bhatnagar
Greenhorn
Posts: 26
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 33
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 26
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 33
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
because that is the property of protected variables.

They can be access only via the subclass.
 
Geetha Arthanari
Greenhorn
Posts: 25
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For a subclass outside the package, the protected member can be accessed only through inheritance not by references.
 
Manikandan Jayaraman
Ranch Hand
Posts: 230
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Sarikaa Bhatnagar
Greenhorn
Posts: 26
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks a lot!!!
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic