Understand protected modifier in java

Understanding most critical access modifier  protected in java?


We all know Java has three access modifiers a, public b. protected c. private and four access levels  a.public b. protected c. private d. default among them protected is the most critical modifier to understand.


Definition of protected
protected is same as default modifier, which can be accessed by other classes in the same package but the only difference is it can also be accessed by sub classes from outside packages through inheritance.

Now there are two catch points

1. What do you mean by accessed?
2. What do you mean by access through inheritance?

1. What do you mean by accessed?


In Java, we can access properties of other classes by two ways

a. Association (HAS A)
b. Inheritance (IS-A)

Scenario a.

package com.bar;
public class Bar
{
 protected String greet = "Hello";
}



package com.foo;
public class Foo extends Bar
{
Bar bar = new Bar(); // Bar HAS A relationship with Foo(Association)

bar.greet; //not compiled as no visibility through association

}



Scenario b

package com.bar
Class Bar
{
 protected String greet = "Hello";
}


package com.foo
Class Foo extends Bar
{


System.out.println(greet); //accessd through Inheritence so it prints Hello

}



Association means a class has a reference to another class  as you see in Scenario a.

Inheritance means  a class inheriting parent class property.
The Answer is  no as by rule protected is visible only through inheritance so although class Foo extends Bar but we are trying to access greet variable through association which is not acceptable in Java



On another hand, in Scenario 2 will compile fine and show Hello as Foo inherited Bar's greet property though Inheritance by definitions which is acceptable.

Now, adding bit complexity in it
suppose,
the class zoo is in the package com.foo now If I write following code snippet in Zoo


Foo foo = new Foo();
foo.greet;

will it be compile?

Think about it.......

The Answer is no as I said earlier by Association (different package ) you can't ever access greet. but in Same package you do.

See the relationship picture to remember the rule.

Protected access modifiers