nirjari patel wrote:My confusion is, methods callToAClassprintAndReturnSomething() and callToBClassprintAndReturnSomething() , both have void return type as void. But methods being called in them printAndReturnSomething() and printAndReturnSomething() both have return types of objects of class A and class B. So how does this work ? How can the void return type accept returned objects of class A and class B ?
If method X calls method Y, the return type of X has nothing to do with the return type of Y. Your main method returns void, right? If we couldn't call non-void methods from void methods, then it would be impossible to
ever call them. Main is void, so it could only call non-void methods, which in turn would only be able to call non-void methods, and so on.
In what way are you thinking that the x or the y above have anything to do with foo()'s return type? (I'm not being sarcastic here. I'm sincerely asking, in case you're still confused, so that I can try to understand the way you're picturing these pieces fitting together.)
Finally, it just occurred to me what your might be getting confused with. Possibly one of these:
In the first case, if append() returned void, we couldn't do that. It would be like trying to do
void.append("a"). But since append() returns a reference to a StringBuilder, we can use the result of append as a StringBuilder reference just like any other SB reference expression.
In the second case, if currentTimeMillis() returned void, it would be like trying to call
println(void). But it returns a long, so we're invoking the
println(long) method.