A protected class member in Java by convention, can be accessed only from within the class where it is declared or from it’s direct descendant inheriting class. A protected class member in the following example, however can be accessed from other class without using any inheritance concept in Java.
package classmembers;
final class Demo
{
private int a=10;
protected int b=20;
public int c=30;
public Demo(int a, int b, int c)
{
this.a=a;
this.b=b;
this.c=c;
}
protected void show()
{
System.out.println("a = "+a);
}
}
final public class Main
{
public static void main(String[] args)
{
Demo d=new Demo(10, 20, 30);
//System.out.print("\n"+d.a); Wrong, since a has private access
d.show(); //Working, even if it is protected
System.out.print("\n"+d.b); //Working, even if it is protected
System.out.print("\n"+d.c); //Working, since it is public, obviously
}
}
In this example, the protected class members b of type int and the method show() declared within the class Demo are being accessed through the main() method even if they are explicitly declared as protected and no any inheritance concept is used.
In such a scenario, what is the difference between a protected class member and a public class member in Java. Are they same?
This is because protected members can also be accessed from classes in the same package. (And both
MainandDemoare in theclassmemberspackage.)The modifiers only differ if the classes are of different packages.
Have a look at the table at the official tutorial: Controlling Access to Members of a Class