user2567495
user2567495

Reputation: 11

Java Protected Variables can be accessed inside same package without inheritance how?

Please see below program and comments:

Please tell me how another class can access protected member without inheritance? I have compiled and run this program at my end.

class Sample3
{
   final protected String Var1 = "Sample 3 Final Varaible";
   final private String Var2 = "Sample 3 Final Varaible";
}//class Sample3

class Sample4
{
 public static void main(String args[])
 {
    Sample3 s3=new Sample3();
    //System.out.println(s3.Var2);// Line 12 : this is not accessible as the Private member is being accessed 
    System.out.println(s3.Var1);//Line 13 : this access the protected member but i have not used inheritance between 2 classes Sample3 and Sample4
 }//end of main
}/class Sample4

Var1 is the Class protected member, Var2 is the class private member.

I am creating the Object of the Sample3 inside Sample4. Line 12 is clearly an error but how it can compile line 13?

Upvotes: 0

Views: 3374

Answers (2)

Malwaregeek
Malwaregeek

Reputation: 2274

Remember protected as this way- default+inheritance. Protected access modifier allows access in same package + subclass in other packages.

Upvotes: 2

devrobf
devrobf

Reputation: 7213

This is the correct behaviour. protected allows the member to be seen by all classes in the same package, not just subclasses. See http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html.

Upvotes: 4

Related Questions