The Anatomy of a Java Application |
The last line of theimport java.util.Date; class DateApp { public static void main(String args[]) { Date today = new Date(); System.out.println(today); } }main()
method uses the System class from the java.lang package to display the current date and time. First, let's break down the line of code that invokes theprintln
method, then look at the details of the argument passed to it.Static Methods and Variables
In the Java statementSystem.out.println(today);System.out
refers to theout
variable of the System class. As you can see, to refer an class's static variables and methods, you use a syntax similar to the C and C++ syntax for obtaining the elements in a structure. You join the class's name and the name of the static method or static variable together with a period ('.').Notice that the application never instantiated the System class and that
out
is referred to directly from the class. This is becauseout
is declared as a static variable--a variable associated with the class rather than with an instance of the class. You can also associate methods with a class--static methods-- usingstatic
.Instance Methods and Variables
Methods and variables that are not declared asstatic
are known as instance methods and instance variables. To refer to instance methods and variables, you must instantiate the class first, then obtain the methods and variables from the instance.System's
out
variable is an object, an instance of the PrintStream class (from the java.io package), that implements the standard output stream. The Standard Output Stream in The Nuts and Bolts of the Java Language discusses the standard output stream in detail. For now, just think of it as a convenient place for an application to display its results.System creates
out
, and all of its other static variables, when the System class is loaded into the application. The next part of the Java statement calls one ofout
's instance methods:println()
.out.println()As you see, you refer to an object's instance methods and variables similar to the way you refer a class's static methods and variables. You join the object's name and the name of the instance method or instance variable together with a period ('.').
The Java compiler allows you to cascade these references to static and instance methods and variables together and use the construct that appears in the listing above
System.out.println()Sum it Up
Static variables and methods are also known as class variables or class methods because each class variable and each class method occurs once per class. Instance methods and variables occur once per instance of a class.
The Anatomy of a Java Application |