Section 7.7. Notes on Declaring and Using Methods


7.7. Notes on Declaring and Using Methods

There are three ways to call a method:

  1. Using a method name by itself to call another method of the same class or modulesuch as Maximum(number1, number2, number3) in line 56 of Fig. 7.4.

  2. Using a variable that contains a reference to an object, followed by a dot (.) and the method name to call a method of the referenced objectsuch as the method call in line 10 of Fig. 7.5, gradeBook1.DisplayGradeReport(), which calls a method of class GradeBook from the Main method of module GradeBookTest.

  3. Using the class or module name and a dot (.) to call a Shared method of a class or module (all methods of a module are implicitly Shared). One example of this is Math.Sqrt(900.0) in Section 7.5.

Note that a Shared method can call only other Shared methods of the same class directly (i.e., using the method name by itself) and can manipulate only Shared members in the same class directly. To access the class's non-Shared members, a Shared method must use a reference to an object of the class. Recall that Shared methods relate to the class, whereas non-Shared methods are associated with a specific instance (object) of the class and may manipulate the instance variables of that object. Many objects of a class, each with its own copies of the instance variables, may exist at the same time. Suppose a Shared method were to invoke a non-Shared 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-Shared method was invoked? Thus, a Shared method cannot access non-Shared members of the same class directly.

Control can be returned to the statement that calls a method by using the Return statement or by reaching the end of the method (End Sub or End Function). If the method does not return a result but uses a Return statement to return control to the calling method, the Return statement cannot include an expression. If the method does return a result, the statement


Return expression

evaluates the expression, then returns the result to the caller.

Common Programming Error 7.4

Declaring a method outside the body of a class or module declaration or inside the body of another method is a syntax error.


Common Programming Error 7.5

Omitting the return-value-type in a method declaration, if that method is a function, is a syntax error.


Common Programming Error 7.6

Redeclaring a method parameter as a local variable in the method's body is a compilation error.


Common Programming Error 7.7

Returning a value from a method that is a subroutine is a compilation error.




Visual BasicR 2005 for Programmers. DeitelR Developer Series
Visual Basic 2005 for Programmers (2nd Edition)
ISBN: 013225140X
EAN: 2147483647
Year: 2004
Pages: 435

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net