Protected Access Specifier
As we have lardy said, there also exists the protected access specifier in addition to the public and private access specifiers. This specifier can be applied to both instance variables and methods. It offers a level of protection intermediate to that offered by the private and public specifiers. Variables and methods declared protected are accessible from the classes defined in the same package and also from subclasses which are defined in other packages. To illustrate the use of protected access specifier, we first see how we create a package and include a class in a particular package. A package isn't created by any explicit statement. It is automatically created when a class is specified to be a part of that package. A class is declared to be a part of a particular package by including the package statement at the top of the class. The package statement should be the first statement in a program file, even before import declarations. However comments are allowed to be placed before the package statement. The following program defines a class A and places it in the package named mypackage1. Package names are by convention written in all lowercase letters even if they consist of multiple words.
package mypackage1;
class A {
protected int num;
}
class A {
protected int num;
}
And, the following defines a new class B in package mypackage2. This class consists of a variable of type A. When one tries to access the variable num of class A, compilation errors occur. This is because, num has protected access. It is accessible only within the same package and within its subclasses.
package mypackage2;
class B {
A objA;
public B() {
objA = new A();
objA.num = 34; // not allowed
}
}
class B {
A objA;
public B() {
objA = new A();
objA.num = 34; // not allowed
}
}
The above access is permitted if B is defined to be a subclass of A or if it in defined in the same package as that to which A belongs, even if it is not declared to be a subclass.
package mypackage2;
class B extends A {
A objA;
public B() {
objA = new A();
objA.num = 34; // not allowed
}
}
class B extends A {
A objA;
public B() {
objA = new A();
objA.num = 34; // not allowed
}
}
When a class is not specified to be a part of any package, it is placed in the default package. This default package and the java.lang package are imported into all classes implicitly. A package can in turn contain other packages. For example, we can have another package p2 in the package mypackage in eth following way.
package mypackage.p2;
class B {
}
class B {
}
Now, with respect to access restrictions, the class A and B are considered to be in different packages. Protected variables of class B are not accessible from class A. Similarly, protected variables of class A are not accessible from B.
0 comments:
Post a Comment
Let us know your responses and feedback