Java Reference
In-Depth Information
When a static method of a class is called, an instance of that class may not exist. Therefore, it is not allowed to
refer to instance variables from inside a static method. Class variables exist as soon as the class definition is loaded
into memory. The class definition is always loaded into memory before the first instance of a class is created. Note
that it is not necessary to create an instance of a class to load its definition into memory. JVM guarantees that all class
variables of a class exist before any instances of the class. Therefore, you can always refer to a class variable from
inside an instance method.
a class method (or static method) can refer to only class variables (or static variables) of the class. an instance
method (non-static method) can refer to class variables as well as instance variables of the class.
Tip
Listing 6-7 demonstrate the types of class fields that are accessible inside a method.
Listing 6-7. Accessing Class Fields from Static and Non-static Methods
// MethodType.java
package com.jdojo.cls;
public class MethodType {
static int m = 100; // A static variable
int n = 200; // An instance variable
// Declare a static method
static void printM() {
/* We can refer to only static variable m in this method
because you are inside a static method */
System.out.println("printM() - m = " + m);
/* System.out.println("printM() - n = " + n); */ /* A compile-time error */
}
// Declare an instance method
void printMN() {
/* We can refer to both static and instance variables m and n in this method */
System.out.println("printMN() - m = " + m);
System.out.println("printMN() - n = " + n);
}
}
The MethodType class declares m as a static variable and n as a non-static variable. It declares printM() as a
static method and printMN() as an instance method. Inside the printM() method, you can refer to only static
variable m because a static method can refer to only static variables. If you uncomment the commented statement
inside the printM() method, the code will not compile because a static method will attempt to access a non-static
variable n . The printMN() method is a non-static method and it can access both static variable m and non-static
variable n . Next, you would like to invoke the printM() and printMN() methods of the MethodType class. The next
section discusses how to invoke a method.
 
 
Search WWH ::




Custom Search