In object-oriented programming, is the object part of the method call? [closed]

StackOverflow https://stackoverflow.com/questions/8993707

  •  13-11-2019
  •  | 
  •  

Pergunta

For example, imagine I have an object defined like so:

public class Example {
    public void doSomething() {
        // does something
    }
}

If I wanted to call doSomething, I'd need an instance of Example:

Example foo = new Example();
foo.doSomething();  // doSomething is executed

My question is, what part of the line foo.doSomething(); is officially considered the method call?

Is it just the doSomething() part or is it the entire statement including the object (foo.doSomething())?

Foi útil?

Solução

In Java, the whole target.method() is considered part of the method invocation:

http://java.sun.com/docs/books/jls/second_edition/html/expressions.doc.html#20448

This means that if you have code like this:

foo.bar().baz()

...then the whole expression is the method invocation of baz(), and the target of that method invocation is itself another method invocation.

Outras dicas

doSomething is a member of the Example class.
foo is an instance of the Example class.

I don't know if the is a governing body controlling the OOP terminology, but as fat as i'm concerned methods in OOP can't be independent of classes. You have two choices, you call an instance method or a class (static) method. Ether way, you need to give the name of the entity (class or object) you call the method of and the method name. So foo.doSometghing() is the method call.

In short, just the doSomething(). For an instance method (such as your doSomething() method), we would say that you called the method on the object. Every instance method has an extra argument, called this, which represents the object that you called the method on, and the language passes it to the method automatically for you.

doSomething() is the method, and foo is the instance that you called the method on. foo will be implicitly passed as the this parameter.

doSomething() is the method call, foo is the instance of Example that the method is being called on/from.

The dot operator de-references the object foo, and then accesses foo's base object. That object in this case is Example. It then accesses Example's method doSomething() in which case something is done. In this scenario foo is a reference to the object instantiated from the class Example. The dot operator de-references foo, and doSomething() accesses the de-referenced base class in order to call the method.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top