Reputation: 11236
Please let me know if these access levels are possible in java, if not what are the alternatives.
Question 1:
From same class: yes
From subclass same package: yes
From any class same package: no
From subclass outside package: no
From any class outside package: no
and Question 2:
From same class: yes
From subclass same package: yes
From any class same package: no
From subclass outside package: yes
From any class outside package: no
None of the access modifiers(public/private/default/protected) provide the above set of control.
For eg: I have a private member which is only accessible within the same class. How to give it an access control as stated in my first question?
Upvotes: 2
Views: 143
Reputation: 1791
Yes, It's possible. but as mentioned above, it's not achieved by simply using the default available access modifiers. you need to add a getter to control the access to your attribute or method.
package house;
public class Father {
private String secret = "I am your father";
// for Q1 use default, for Q2 use protected
protected String getSecret() {
if(this.getClass().getName() != "house.Father") return secret;
else return "some talk about the weather...";
}
}
This getter allow the access by inheritance exclusively, and a direct access to the private attribute is always available. but the access by reference is denied.
Upvotes: 0
Reputation: 947
The subclass in different package cannot be given separate access levels.
Only possible work around is to re-structure the packages :-(
Upvotes: 0
Reputation: 14373
The access specifiers available in java doesn't match your requirements.
There is no distinction for
From subclass same package:
From subclass outside package:
Upvotes: 1
Reputation: 40066
No, it is not possible to achieve the 2 access level requirement you want.
There are only 4 access levels in Java, public, default, protected and private. None of them matches what you are looking for.
Upvotes: 0
Reputation: 46438
This breakdown should help you decide the answer.
From same class: //private, default, protected, public
From subclass same package: //default, protected, public
From any class same package: //default, protected public
From subclass outside package: //protected, public
From any class outside package: //public
Upvotes: 0
Reputation: 143946
You should be able to find them all here: http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
Upvotes: 0