You cannot restrict access because you have already allowed more access in the superclass. eg.
SuperClass sc = new SubClass(); sc.foo(); // is package local, not private.
Access to sc determined by the type of link sc , and not what it refers to, because the compiler cannot know in all cases what type of object is at run time. For this to be a safe assumption, the subclass must fulfill the contract provided by the parent, or it cannot be a valid subclass. This is no different from the parent saying that the method is implemented, but a subclass saying that it (or is not available)
You can get around this by saying that you can access the subclass method only through the parent, and not directly. The problem is that you do not know when the parent can add the method, and when you create the private method, you do this because you want it to be private and inaccessible in another way.
BTW You can still access the private method using reflection, which has a side effect that causes all kinds of problems for the JVM. for example, it must support private methods, even if it can determine that it cannot be called normally.
In short, you want the code to mean what it says and not have a forked personality. This is either a local package, or it is not private, and not something like a gap between them, but not really. This is not such a problem. that is, if the subclass is publicly available. It just means that the subclass can be used in more places than the parent, just as it can implement more methods.
Peter Lawrey
source share