Who or what is the "caller"?
So I'm a little confused about the term "caller" and I was wondering if someone could please explain it to me. I'm getting confused when certain examples talk about something being returned to the "caller", as I'm not sure what the caller really is.
eg.
public class Book {
String title;
public Book(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
public static void main(String[] int) {
Book b = new Book;
System.out.println("The book's title is: " + b.getTitle());
}
}
So here we have a Book class with a simple getter method defined. In main, when we use 'b.getTitle()', would the object b then be the 'caller' since the method getTitle() is invoked on that object?
Any explanation here would be greatly appreciated.
Thanks!
Re: Who or what is the "caller"?
The caller is simply the code that calls the method. In your example, the caller would be the main method. You could make a different class that uses that method, and that would be a different caller.
Re: Who or what is the "caller"?
Quote:
Originally Posted by
KevinWorkman
The caller is simply the code that calls the method. In your example, the caller would be the main method. You could make a different class that uses that method, and that would be a different caller.
So wouldn't the caller always be a method then, since you cant have random code living outside a method in some class somewhere. When would the actual class be the caller? I guess I could see maybe if you are going to use some method to do some initialization inside a class possibly. Any thoughts?
Re: Who or what is the "caller"?
Quote:
Originally Posted by
js82
So wouldn't the caller always be a method then, since you cant have random code living outside a method in some class somewhere. When would the actual class be the caller? I guess I could see maybe if you are going to use some method to do some initialization inside a class possibly. Any thoughts?
I think you're complicating this a bit more than it deserves. The caller is just a way to refer to the code that's calling the method, usually to differentiate between different places in the code that calls it. So how can a method be called? From another method, from a constructor, from a static block, etc. I don't think you should worry about it too much. The caller is just the place in code that calls your method. For little examples like yours it's a useless distinction, but think about bigger programs that might call the same function in multiple places- then it might be useful to refer to "the caller" since that could be any number of actual lines of code.