Monday, June 26, 2017
Protected access modifier in Java
Protected access modifier in Java
Like public and private, protected is also a access modifier which has different visibility scope and it is also one of the keyword in java. Its scope are valid to the other packages but it should be within the sub-class. Like private we can be able to use protected scope with the constructor, methods, variables and inner classes. Accessing protected member outside its scope will give compilation error saying " Not Visible ".
Note : We cannot use protected with the class.
What are the possible areas where protected members can be used ?
It can be used with constructor, methods, variables and inner classes.
Members of the class declared as protected can be accessible outside the package but with the current sub-class object in the other packages. We have two scopes in java:
1. Class Scope
- Sub-class in the same package --> Visible
- Sub-class in other packages --> Visible
- Another class in the same package --> Visible
- Non- subclass in other package --> Not visible
2. Package Scope
- Within the same package ---> Visible
- Outside the package ---> Visible but in the current sub-class.
Protected with Constructor
Declaring protected keyword before the name of constructor will make it protected. Protected constructor of a class are visible in another class sub-class which is defined in another package and can only be accessible with that sub-class object. For ex-
D.java in com package
------------------------------
package com;
public class D {
protected D(){} // Protected constructor
public static void main(String[] args) {
}
}
E.java in def package
-----------------------------
package def;
import com.D;
public class E extends D {
public static void main(String[] args) {
E e = new E();
D d = new D(); // " Visible "
}
}
Protected with variable
Like constructor variable declared as protected are also visible with the sub-class object in another package. For ex-
------------------------------
package com;
public class D {
protected int x=10; // Protected variable
public static void main(String[] args) {
}
}
E.java in def package
-----------------------------
package def;
import com.D;
public class E extends D {
public static void main(String[] args) {
E e = new E();
System.out.println(e.x);
D d = new D();
System.out.pritln(d.x); // "Visible"
}
}
Protected with the method
Like variable method declared as protected can be accessed with the sub-class object defined in another package. For ex-
-----------------------------
package com;
public class D {
protected void display(){
System.out.println("protected method");
} // Protected method
public static void main(String[] args) {
}
}
E.java in def package
----------------------------
package def;
import com.D;
public class E extends D {
public static void main(String[] args) {
E e = new E(); // Current class object
e.display();
}
}
Available link for download