Java Reference
In-Depth Information
Invoking a Method
Executing the code in the body of a method is called invoking (or calling) a method. Instance methods and class
methods are invoked differently. An instance method is invoked on an instance of the class using dot notation.
<<instance reference>>.<<instance method name>>(<<actual parameters>>)
Note that you must have a reference to an instance of a class before calling an instance method of that class. For
example, you can write the following snippet of code to invoke the printMN() instance method of the MethodType
class listed in Listing 6-7:
// Create an instance of MethodType class and
// store its reference in mt reference variable
MethodType mt = new MethodType();
// Invoke the printMN() instance method using the mt reference variable
mt.printMN();
To invoke a class method, you use dot notation with the class name. The following snippet of code invokes the
printM() class method of the MethodType class:
// Invoke the printM() class method
MethodType.printM();
Whatever belongs to a class also belongs to all instances of that class. You can also invoke a class method using a
reference of an instance of that class.
MethodType mt = new MethodType();
mt.printM(); // Call the class method using an instance mt
Which is a better way to invoke a class method: using the class name or using an instance reference? Both ways
do the same job. However, using the class name to invoke a class method is more intuitive than using an instance
reference. This topic uses a class name to invoke a class method, except for the purpose of demonstrating that you can
also use an instance reference to invoke a class method. Listing 6-8 demonstrates how to invoke an instance method
and a class method of a class. Note that the output shows the same result when you invoke the class method printM()
using the class name or an instance reference.
Listing 6-8. Examples of Invoking Instance Methods and Class Methods of a Class
// MethodTypeTest.java
package com.jdojo.cls;
public class MethodTypeTest {
public static void main(String[] args) {
// Create an instance of the MethodTYpe class
MethodType mt = new MethodType();
System.out.println("Invoking instance method...");
// Invoke the instance method
mt.printMN();
System.out.println("Invoking class method on class name...");
 
Search WWH ::




Custom Search