What is the difference between message-passing and method-invocation?

后端 未结 5 940
盖世英雄少女心
盖世英雄少女心 2021-02-02 07:51

Is there a difference between message-passing and method-invocation, or can they be considered equivalent? This is probably specific to the language; many languages don\'t suppo

5条回答
  •  青春惊慌失措
    2021-02-02 08:18

    Using Objective-C as an example of messages and Java for methods, the major difference is that when you pass messages, the Object decides how it wants to handle that message (usually results in an instance method in the Object being called).

    In Java however, method invocation is a more static thing, because you must have a reference to an Object of the type you are calling the method on, and a method with the same name and type signature must exist in that type, or the compiler will complain. What is interesting is the actual call is dynamic, although this is not obvious to the programmer.

    For example, consider a class such as

    class MyClass {
        void doSomething() {}
    }
    
    class AnotherClass {
        void someMethod() {
            Object object = new Object();
            object.doSomething(); // compiler checks and complains that Object contains no such method.
    
            // However, through an explicit cast, you can calm the compiler down,
            // even though your program will crash at runtime
            ((MyClass) object).doSomething(); // syntactically valid, yet incorrect
        }
    }
    

    In Objective-C however, the compiler simply issues you a warning for passing a message to an Object that it thinks the Object may not understand, but ignoring it doesn't stop your program from executing.

    While this is very powerful and flexible, it can result in hard-to-find bugs when used incorrectly because of stack corruption.

    Adapted from the article here. Also see this article for more information.

提交回复
热议问题