Data is passed to a function "explicitly" whereas a method is "implicitly passed" to the object for which it was called.
Please could you explain the difference between these two ways of passing data? An example in java or c# would help.
Data is passed to a function "explicitly" whereas a method is "implicitly passed" to the object for which it was called.
Please could you explain the difference between these two ways of passing data? An example in java or c# would help.
The language Java and Python are good examples in illustrating this. In Python, the object is passed explicitly whenever a method of a class is defined:
class Example(object):
def method(self, a, b):
print a, b
# The variable self can be used to access the current object
Here, the object self
is passed explicitly as the first argument. This means that
e = Example()
e.method(3, 4)
is effectively the same as calling method(e, 3, 4)
if method
were a function.
However, in Java the first argument is not explicitly mentioned:
public class Example {
public void method(int a, int b) {
System.out.println(a + " " + b);
// The variable this can be used to access the current object
}
}
In Java, it would be:
Example e = Example();
e.method(3, 4);
The instance e
is passed to method
as well but the special variable this
can be used to access it.
Of course, for functions each argument is passed explicitly because each argument is mentioned in both the function definition and where the function is called. If we define
def func(a, b, c):
print a, b, c
then we can call it with func(1, 2, 3)
which means all arguments are explicitly passed.
In this context a method can be considered to be a function that has access to the object it's bound to. Any properties of this object can be accessed from the method, even though they didn't appear in the signature of the function. You didn't specify a language, but let me give an example in PHP as it's pretty prevalent and easy to read even if you didn't use it.
Edit: the languages were added after I wrote this; maybe someone can translate this to one of those languages if needed.
<?php
/* Explicit passing to a function */
function f($a, b)
{
return $a + b;
}
// f(1, 2) == 3
class C
{
public $a, $b;
/* $a and $b are not in the parameter list. They're accessed via the special $this variable that points to the current object. */
public function m()
{
return $this->a + $this->b;
}
}
$o = new C();
$o->a = 1;
$o->b = 2;
//$o->m() == 3