9/1/2021 Java Tutorials - Access protection in java packages
(../[Link])
(../[Link]) (../[Link]) ✏ (../[Link])
(../[Link]) (../[Link])
Java
Programming
Access protection in java packages
Previous ([Link])
Next ([Link])
In java, the access modifiers define the accessibility of the class and its members. For example,
private members are accessible within the same class members only. Java has four access
modifiers, and they are default, private, protected, and public.
In java, the package is a container of classes, sub-classes, interfaces, and sub-packages. The
class acts as a container of data and methods. So, the access modifier decides the accessibility of
class members across the different packages.
In java, the accessibility of the members of a class or interface depends on its access specifiers.
The following table provides information about the visibility of both data members and methods.
[Link]/java/[Link] 1/4
9/1/2021 Java Tutorials - Access protection in java packages
🔔 The public members can be accessed everywhere.
🔔 The private members can be accessed only inside the same class.
🔔 The protected members are accessible to every child class (same package or other
packages).
🔔 The default members are accessible within the same package but not outside the
package.
Let's look at the following example java code.
[Link]/java/[Link] 2/4
9/1/2021 Java Tutorials - Access protection in java packages
class ParentClass{
int a = 10;
public int b = 20;
protected int c = 30;
private int d = 40;
void showData() {
[Link]("Inside ParentClass");
[Link]("a = " + a);
[Link]("b = " + b);
[Link]("c = " + c);
[Link]("d = " + d);
}
class ChildClass extends ParentClass{
void accessData() {
[Link]("Inside ChildClass");
[Link]("a = " + a);
[Link]("b = " + b);
[Link]("c = " + c);
//[Link]("d = " + d); // private member can't be accessed
public class AccessModifiersExample {
public static void main(String[] args) {
ChildClass obj = new ChildClass();
[Link]();
[Link]();
When we run this code, it produce the following output.
[Link]/java/[Link] 3/4
9/1/2021 Java Tutorials - Access protection in java packages
Previous ([Link])
Next ([Link])
Courses (../[Link]) | Downloads (../[Link]) | About Us (../[Link]) | Contcat Us
(../[Link])
Website designed by Rajinikanth B
([Link]
([Link] ([Link]
([Link]
[Link]/java/[Link] 4/4