声明类属性受保护还是公共?
我在包 com.practise.mypackageone.MyClass 中有一个类
,MyClass 类有一个方法
/* Modifier */ void show()
{
// some code here
}
,我希望该方法只能从另一个包类(例如
com.practise.mypackagesecond.SecondClass)
访问现在,如果我将该方法公开,它将可以访问到我不想要的任何地方。 如果我将其设置为受保护,则 SecondClass 必须扩展 MyClass 才能访问它。
但任何其他包类也可以扩展我的类来访问该方法。
我怎样才能防止这种情况发生?
I have a class say within a package com.practise.mypackageone.MyClass
Class MyClass has a method
/* Modifier */ void show()
{
// some code here
}
I want this method to be only accessible from another package class say
com.practise.mypackagesecond.SecondClass
Now if I made the method public it will accessible to everywhere which I dont want.
and if I made it protected then SecondClass has to extend MyClass in order to access it.
But any other package class can also extend my class to access that method.
How can I prevent that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将类放在同一个包中,并将方法包设置为私有(默认修饰符)。否则我认为你想要的东西是无法实现的。
Put the classes in the same package and make the method package private(the default modifier). Otherwise I think what you want is not achievable.
第一个包中的类可以从第二个包中扩展一个类,如下所示,并且它们可以按照自己的意愿实现 show() 方法:
如果第二个包中只有一个类(例如 ViewManager)需要调用此方法时,您可能希望将此 Showable 嵌入其中,以便只有此类才能调用 show() 方法。
但这不是一个非常干净的设计。
The classes in the 1st package can extend a class from the 2nd package that looks like this, and they can implement the show() method as they wish:
If there is only one class in the 2nd package (say, ViewManager) that needs to call this method you might want to embed this Showable in it so that only this class can call the show() method.
It is not a very clean design though.