如何限制同一个类中的方法调用?
最近我参加了一次面试,面试官问了一个关于方法访问限制的问题。
问:在一个类中我有 3 个方法(即 method1()、method2()、method3()),我在同一个类中调用这 3 个方法,但我应该只调用前 2 个方法,我应该限制第 3 个方法,所以没有人应该调用method3()。我该怎么办?
面试官也给出了提示(即通过使用对象或引用)。采访结束时他说答案仅供参考。
我对他的问题感到困惑,有人知道他所指的是什么吗?
谢谢, 兰吉斯
Recently I attended an interview, the interviewer is asking a question about restricting of method access.
Q: In one class I have 3 methods (i.e. method1(), method2(), method3()), I am calling those 3 methods in same class, but I should call only first 2 method, I should restrict 3rd method, so nobody should call method3(). How can I do it ?
The interviewer gave an hint also (i.e. by using object or reference) . And at the end of interview he said answer is reference.
I was confused with his question, any body having an idea of what he is pointing to ?
Thanks,
Ranjith
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
也许他的意思是method1和method 2应该是静态的(即不需要对现有实例的引用),而method3应该是实例方法?
在这种情况下,可以从 Main 内部调用前两个方法,而无需实例化对象引用。
Maybe he meant that method1 and method 2 should be static (i. e. not needing a reference to an existing instance), and method3 should be an instance method?
In this case, the first two methods could be called from within Main without instantiating an object reference.
好吧,你的问题不是很清楚......但是如果
method3()
只能从创建它的类中调用,你可以将其设为私有。如果这不是您要问的,请澄清问题。
Well, your question isn't very clear... but if
method3()
should only be callable from within the class that created it, you can just make it private.If that isn't what you're asking, please clarify the question.
不知道这次采访是否是想加深您对 Java 语言中 public、protected 和 private 访问级别修饰符的理解?
I wonder if the interview was trying to elicit your understanding of public, protected and private access level modifiers in the Java language?