In Java programming language, there are four access specifiers, private, default, protected and public
.
private The methods and instance variables declared as private can be accessed within the class only. Private members are not accessible from any other location.
default If access specifier is not mentioned at the time of variable declaration, the scope is known as default access specifier. The default variables and methods can be accessed within the package.
protected The methods and instance variables declared as protected can be accessed within the package and can also be accessed from other package if inheritance relation exists.
public The methods and instance variables declared as public can be accessed from anywhere.
Example
In the following example, class A contains four variables with different access specifiers.
A.java
package com.t4b.java.pkg1;
public class A {
private int x = 10;
int y = 20;
protected int z = 30;
public int w = 40;
}
Here, we are defining a sub class B in the same package and we are trying to access the variables of A class. All the variables except private one are accessible in sub-class.
B.java
package com.t4b.java.pkg1;
public class B extends A {
void print() {
//System.out.println(x);
System.out.println(y);
System.out.println(z);
System.out.println(w);
}
}
Here, we are defining a sub class B in the different package and we are trying to access the variables of A class. The private and default variables are not accessible in sub-class.
B.java
package com.t4b.java.pkg2;
import com.t4b.java.pkg1.A;
public class B extends A {
void print() {
//System.out.println(x);
//System.out.println(y);
System.out.println(z);
System.out.println(w);
}
}
In the following programs, we are trying to access the variables of class A a different class, where inheritance relationship does not exist.
Here, we are creating an object of class A in main method of class Test. If the Test class belongs to same package with class A, all the members (except private member) of class A are accessible as shown below.
Test.java
package com.t4b.java.pkg1;
public class Test {
public static void main(String[] args) {
A a = new A();
// System.out.println(a.x);
System.out.println(a.y);
System.out.println(a.z);
System.out.println(a.w);
}
}
If the Test class belongs to a different class, only public member of class A is accessible as shown in the following example.
Test.java
package com.t4b.java.pkg2;
import com.t4b.java.pkg1.A;
public class Test {
public static void main(String[] args) {
A a = new A();
// System.out.println(a.x);
// System.out.println(a.y);
// System.out.println(a.z);
System.out.println(a.w);
}
}
Hence, you can understand that the protected member is accissible from any where within the package as well as from other package if there exists Inheritance relationship.
Happy Exploring!
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.