I have a class called A in package1 and another class called C in package2. Class C extends class A.
A has an instance variable which is declared like this:
<
Protected means :
a)This member will be accessible to all classes in same package through A object’s reference.
b) For different package, this will be accessible only inside Subclasses of A say B and the reference used can be of B instance or of any subclass of B.
Let's take an example:
Let A be parent class in some package say com.ex1
Let B ,C be classes in different package w.r.t to A say com.ex2
. Also, B extends A
and C extends B
.
We will see how we can use protected field of A inside B (a subclass of A)
A's code:
public class A {
protected int a = 10;
}
B's code:
public class B extends A {
public void printUsingInheritance() {
// Using this
System.out.println(this.a);
}
public void printUsingInstantiation() {
// Using instance of B
B b = new B();
System.out.println(b.a);
// Using instance of C as C is subclass of B
C c = new C();
System.out.println(c.a);
A a = new A();
System.out.println(a.a); // Compilation error as A is not subclass of B
}
}
C's code:
public class C extends B {
}
For protected Static :
Same rules apply except that in b) now it is accessible in any subclass of A by A's class reference. Reference