[英]Java any way to keep a method usable only by class and subclasses?
I am fully aware of how public
, protected
and private
in Java work. 我完全了解Java中public
, protected
和private
的工作方式。 I was wondering if there is a way to mimic a modifier in between private and protected. 我想知道是否可以在私有和受保护之间模拟修饰符。 I want only a class and its children to be able to access its children. 我只希望一个班级及其子级能够访问其子级。
I want to do this because I have a class, Savable
that stores an int databaseID
. 我想这样做是因为我有一个Savable
类,它存储一个int databaseID
。 Savable
has a save()
method that stores the DBID then calls protected abstract ContentValues getSaveData ()
to obtain any other information from its children to write into the DB. Savable
有一个save()
方法,该方法存储DBID,然后调用protected abstract ContentValues getSaveData ()
来从其子级获取任何其他信息以写入DB。 This however, is unsafe design. 但是,这是不安全的设计。 ContentValues
will store all of the objects information, private or not to be written into the DB. ContentValues
将存储所有对象信息(私有的或不写入数据库的信息)。
Now, while I could just make save an abstract method in Savable
, I would prefer to keep the structure I have now, as I will be adding data to the Savable
class later on, and I would prefer to never have to expose this data to the user. 现在,尽管我可以在Savable
保存一个抽象方法,但我还是希望保留现在的结构,因为稍后我将数据添加到Savable
类中,并且我希望永远不必将数据公开给用户。
So, is there any way to mimic a children-only modifier in Java? 那么,有什么方法可以模仿Java中仅用于儿童的修饰符? If not, I may store the encrypted value of all the data the user supplies in getSaveData()
. 如果没有,我可以将用户提供的所有数据的加密值存储在getSaveData()
。
Requested code: Removed as it is no longer necessary. 要求的代码:已删除,因为不再需要。
So, is there any way to mimic a children-only modifier in Java? 那么,有什么方法可以模仿Java中仅用于儿童的修饰符?
Nope. 不。 The only access modifiers we've got are the ones you listed. 我们仅有的访问修饰符是您列出的那些。 There's also "default" visibility, aka "package-private", but that does not make elements accessible to subclasses. 还有“默认”可见性,也就是“ package-private”,但这不能使元素可用于子类。 So you could probably just use protected
and not worry about it. 因此,您可能只使用protected
而不必担心。
It sounds like a better solution might be a refactor of your code, but there's not much concrete in your question to go on. 听起来更好的解决方案可能是对代码进行重构,但是您的问题没有什么具体的。
我能想到的唯一方法是将方法设置为protected
,并将类放入其自己的包中。
If you yourself are writing the children then you could make them final
. 如果你自己在写孩子,那么你可以使他们final
。
Mixing this up with the protected
modifier would give you something like what you want. 将其与protected
修饰符混合在一起,将为您提供所需的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.