You’ve seen three ways to call a method:
Using a method name by itself to call a method of the same class—as in line 19 of Fig. 7.3, which calls Maximum(number1, number2, number3)
from Main
.
Using a reference to an object, followed by the member-access operator (.
) and the method name to call a non-static
method of the referenced object—as in line 23 of Fig. 4.12, which called account1.Deposit(depositAmount)
from the Main
method of class AccountTest
.
Using the class name and the member-access operator (.
) to call a static
method of a class—as in lines 12–14 of Fig. 7.3, which each call Console.ReadLine()
, or as in Math.Sqrt(900.0)
in Section 7.3.
You’ve seen three ways to return control to the statement that calls a method:
Reaching the method-ending right brace in a method with return type void
.
When the following statement executes in a method with return type void
return;
When a method returns a result with a statement of the following form in which the expression is evaluated and its result (and control) are returned to the caller:
return expression;
Declaring a method outside the body of a class declaration or inside the body of another method is a syntax error.
Redeclaring a method parameter as a local variable in the method’s body is a compilation error.
Forgetting to return a value from a method that should return one is a compilation error. If a return type other than void
is specified, the method must use a return
statement to return a value, and that value must be consistent with the method’s return type. Returning a value from a method whose return type has been declared void
is a compilation error.
static
Members Can Access Only the Class’s Other static
Members DirectlyA static
method or property can call only other static
methods or properties of the same class directly (i.e., using the method name by itself) and can manipulate only static
variables in the same class directly. To access a class’s non-static
members, a static
method or property must use a reference to an object of that class. Recall that static
methods relate to a class as a whole, whereas non-static
methods are associated with a specific object (instance) of the class and may manipulate the instance variables of that object (as well as the class’s static
members).
Many objects of a class, each with its own copies of the instance variables, may exist at the same time. Suppose a static
method were to invoke a non-static
method directly. How would the method know which object’s instance variables to manipulate? What would happen if no objects of the class existed at the time the non-static
method was invoked?
A static
method cannot access non-static
members of the same class directly.