Can you call non-static method from a static?
November 25, 2015
Posted by on
There are questions on a Java technical interview that even the most entry level junior is expected to give the right answer for. Since I am facing candidates who are not that junior I do not even bother most of the times to ask those questions. I assume that the candidate knows the correct answer. Some time however there are some candidates who I feel from the start they are juniors and to cut the interview short not wasting his/her and my time I ask some of those simple questions. The answers usually reveals the real level of knowledge and we can get to an agreement in short time about the assessed level.
Sometimes I also meet candidates who not only simply do not know the answer but give wrong answer. To know something wrong is worse than not knowing. Out of these very few even insists and tries to explain how I should have interpreted their answer. That is already a personality problem and definitely a no-go in an interview.
One such simple question is:
Can a static method in a class call a non-static method of the same class?
If you know Java a little bit you know the answer: no, it can not. A static method belongs to the class and not the instance. It can even be executed using the name of the class directly without any instance of the class. It can even run when there is not even a single instance of the class in the whole JVM. How could it invoke a normal method that runs attached to an instance?
But then again: the answer from one candidate this time was: yes. And he even started to explain that it may happen that the static method has access to an instance. It may get an instance as a method argument and through that reference it can call an instance method. That person was right. It did not, however, mended the fact that he did not know Java good enough, but as a matter of fact in this very specific question she was right.
What is the morale of the story? You tell.