4

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?

Community
  • 1
  • 1
an00b
  • 11,338
  • 13
  • 64
  • 101
  • @aioobe Thanks for finding that thread. I searched for something similar but couldn't find it for some reason. The answers there are very educating. +1. – an00b Mar 23 '11 at 13:34

2 Answers2

8

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.

fredoverflow
  • 256,549
  • 94
  • 388
  • 662
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • 7
    So in Java, developers do not maliciously hack their own programs, and in C++ they do? :) – an00b Mar 23 '11 at 13:32
  • Java is mimalist on features than C++. For example, Java doesn't even support signed int, but C++ developers appear to find it useful. ;) Basically if there is any doubt whether a feature is really useful it doesn't get included. (E.g. even closures are not planned for Java 7) – Peter Lawrey Mar 23 '11 at 13:35
  • 2
    Its unfortunate Java can't do what the asker wants. I don't use scoping to keep bad guys from attacking me, I use scoping to keep me from _mistakenly_ attacking myself. Protected doesn't protect me ): – chessofnerd Jan 29 '14 at 21:11
2

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 :)

Victor Parmar
  • 5,719
  • 6
  • 33
  • 36
  • Yes, I know. I am a total newbie to Java, so I am trying to understand the mindset of the language, not only the syntax. :) – an00b Mar 23 '11 at 13:44