简体   繁体   中英

Is the “caller” in Java the same as the “receiver” in Ruby?

If I say

x.hello()

In Java, object x is "calling" the method it contains.

In Ruby, object x is "receiving" the method it contains.

Is this just different terminology for expressing the same idea or is there a fundamental difference in ideology here?

Coming from Java I find Ruby's "receiver" idea quite baffling. Perhaps someone could explain this in relation to Java?

In your example x is not calling hello() . Whatever object contains that snippet is "calling" (ie, it's the "caller"). In Java, x can be referred to as the receiver; it is receiving the call to the hello() method.

The difference is more than terminology. In Java, the VM determines whether a given object "accepts" the message that you're trying to send (ie, the method you're trying to call). If the object's type space doesn't define that method, an exception is thrown and the message is never delivered.

In Ruby, the message is always delivered. The object may find a method that matches it, or it may not, and in the latter case it may throw an exception, or it may not . Rails is built on this fundamental difference. It's one of the reasons why there isn't a DB-backed web app framework as useful as Rails on the Java platform yet (though some are getting close).

Someone correct me if I'm wrong, but I don't think you can apply these terms to Java. Ruby comes from Smalltalk, which uses messages (not methods) to communicate between objects. Technically, when you do myObj.to_s in Ruby, you are sending the to_s message to myObj and it is acting upon that message accordingly. With that model, myObj is indeed the receiver of this message and the class that owns the line where the message was sent is the sender.

In Java, this doesn't exist. You have objects that you call methods on. There are no senders and receivers. You had it right when you said there is a fundamental difference in ideology.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM