In Java programming language, there are four access specifiers, private, default, protected and public
.
Example
In the following example, class A contains four variables with different access specifiers.
A.java
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
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
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
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
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.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.