Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make data member accessible to class and subclass only [duplicate]

Tags:

java

Possible Duplicate:
Why is there no sub-class visibility modifier in Java?

The access level table for Java, shows 4 different options for controlling access to members of a class:

Modifier    Class  Package Subclass World
public      Y      Y       Y        Y
protected   Y      Y       Y        N
no modifier Y      Y       N        N
private     Y      N       N        N

There is no modifier, however, for "accessible to class and subclass only". That is:

Modifier    Class  Package Subclass World
c++prot     Y      N       Y        N

Is it possible at all to define such access level in Java?

If so, how?

If this isn't possible, this must be due to a well thought design principle. If so, what is that principle. In other words, why having such access level in Java isn't a good idea?

like image 674
an00b Avatar asked Dec 28 '22 23:12

an00b


2 Answers

The design principle is that developers do not maliciously hack their own programs. If you don't trust classes in the same package to behave correctly you have serious non-technical issues IMHO.

The access modifiers are there to restrict accidental errors, and they attempt to stop most error with minimum complexity.

BTW: with reflection/JNI calls you can bypass all access modifiers, so they are not a rock solid security measure IMHO.

like image 197
Peter Lawrey Avatar answered Feb 27 '23 08:02

Peter Lawrey


C++ does not have the concept of packages built-in so when comparing the access modifiers between c++ and Java you should disregard the 'Package' column :)

like image 33
Victor Parmar Avatar answered Feb 27 '23 08:02

Victor Parmar