When you instantiate an object from a class, memory is reserved for each instance field in the class. For example, if a class contains 20 data fields, when you create one object from that class, enough memory is reserved to hold 20 values for that object. Fortunately, it is not necessary to store a separate copy of each variable and method for each instantiation of a class. Usually, you want each instantiation of a class to have its own data fields. When you want each object to have a unique field value, you do not define the field as static. When you create a method for a class, any object can use the same method. Luckily, in Java just one copy of each method in a class is stored, and all instantiated objects can use that copy.
Every object in Java is uniquely identified by its this reference. The this reference is the “handle”(pointer) to the object that is used to invoke methods or explicitly reference instance variables.
The “this” reference is the mechanism that is used to tie them together at run-time. The this reference as a hidden first argument to every non-static class method. Static “class” methods do not have a this reference passed to them.
It is not possible to refer to the this variable in a static method of a class.
class Foo {
int x;
static int f() { return this.x; } // ERROR
}
Commonly static methods are used all the time in Java.
import java.net.*; // need to import InetAddress class
publicclass Host {
static String host;
static String user;
staticfinalinterr = -1; // same as const int err = -1 in C++
publicstaticvoid main (String[] args)
{
try {
InetAddress addr = InetAddress.getLocalHost();
host = addr.getHostName();
user = System.getProperty("user.name");
System.out.println(user + "@" + host); // string concatenation
}catch (Exception e) {
System.err.println(e); System.exit(err);
}
}
}
Output:
mz50947@APACCNSHZJN0764
The System.getProperty method is a static method defined as part of the java.lang.System class that returns a String containing the value of system property “user.name”.