tags:

views:

65

answers:

3

Hi All,

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

+1  A: 

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.

Jon Skeet
No, I am not expecting that answer.To be clear see below example.\nClass A{\npublic void method1(){S.o.p("method1");}\npublic void method2(){S.o.p("method2");}\npublic void method3(){S.o.p("method3");}\n\npublic static void main(String[] args){\nA objA = new A();\nobjA.method1();\nobjA.method2();\nobjA.method3();\n}by using my program I am very well call method3, even if method3() is private or not? but he is asking me that method3() I should not call, the program should not allow it, what should i do here?
Ranjith
What is the use for it if it can't be called by anyone?
picknick
@Ranjith, please add this example code as an update to your original post - it is terribly difficult to read in a comment.
Péter Török
@Ranjith: You've specified a single class... private methods can obviously be called within the same class. But they can't be called from *other* classes. Creating a method that can't be called by *anything* is pointless.
Jon Skeet
Solution: Delete `method3`.
Tom Hawtin - tackline
+1  A: 

I wonder if the interview was trying to elicit your understanding of public, protected and private access level modifiers in the Java language?

bjg
+2  A: 

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.

Frank
yeah may be he is expecting this, thanks.
Ranjith