The visibility of variables is like the visibility of methods; you cannot reduce this visibility. Remember that protected variables are visible outside a direct subclass . Access to it can be obtained from the parent by other members of the package . See this answer for more details.
An ideal solution would be to mess around with a parent-level class. You mentioned that making an object private is not a starter, but if you have access to the class, but it just cannot decrease (possibly due to existing dependencies), you can mix your class structure by abstracting the common interface using methods , and having both ThirdPartyClass and your BaseClass, use this interface. Or you can have in your classroom grandparents two cards, internal and external, that point to the same card, but grandparents always use the internal one. This will allow parents to redefine the external element without disturbing their grandparents.
However, given that you call it a third-party class, I assume that you do not have access to the base class at all.
If you want to break some functions on the main interface, you can get around this with runtime exceptions (mentioned above). Basically, you can override a public variable to throw errors when they do something you don't like. This answer is mentioned above, but I would do it at the variable level (Map) instead of the level of your interface.
If you want to allow READ access to the map ONLY :
protected Map innerPropertyMap = propertyMap; propertyMap = Collections.unmodifiableMap(innerPropertyMap)
You can obviously replace the Map property with your own map implementation. However, it really really works, if you want to disable for all callers on the card , disconnecting only some subscribers will be a pain. (I am sure there is a way to do it if (the caller is the parent) and then returns, otherwise an error, but that would be very very dirty). This means that parents cannot use the class.
Remember that even if you want to hide it from children, if they add themselves to the same package, they can circumvent any restrictions that you indicated with the following:
ThirdPartyClass grandparent = this; // Even if it was hidden, by the inheritance properties you can now access this // Assuming Same Package grandparent.propertyMap.get("Parent-Blocked Chocolate Cookie")
So you have two options:
- Change parent object. If you can change this object (even if you cannot make the field private), you have several structural solutions that you can continue with.
- Change the property to failure in certain use cases. This will include access to grandparents, as a child can always circumvent parental restrictions.
Again, it’s easiest to think of it as a method: if someone can call him grandfather, he can call him grandson.