Previous | Next | Trail Map | Writing Java Programs | The Anatomy of a Java Application


Class vs. Instance

import java.util.Date;
class DateApp {
    public static void main(String args[]) {
        Date today = new Date();
        System.out.println(today);
    }
}
The last line of the 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 the println() method, then look at the details of the argument passed to it.

Class Methods and Variables

Let's take a look at the first segment of the statement:
System.out.println(today);
The construct--System.out--is the full name for the out variable in the System class. Notice that the application never instantiated the System class and that out is referred to directly from the class name. This is because out is a class variable--a variable associated with the class rather than with an instance of the class. You can also associate methods with a class--class methods.

To refer to class variables and methods, you join the class's name and the name of the class method or class variable together with a period ('.').

Instance Methods and Variables

Methods and variables that are not class methods or class variables are known as instance methods and instance variables. To refer to instance methods and variables, you must reference the methods and variables from an instance of the class.

While System's out variable is a class variable, it refers to an instance of the PrintStream class (a member of the java.io package that implements the The Standard Output Stream(in the Writing Java Programs trail) ).

When the System class is loaded into the application, the class instantiates PrintStream and assigns the new PrintStream object to the out class variable. Now, you have an instance of a class so you can call one of its instance methods.

System.out.println()

As you see, you refer to an object's instance methods and variables similar to the way you refer class methods and variables. You join an object reference (System.out) and the name of the instance method or instance variable (printlin()) together with a period ('.').

The Java compiler allows you to cascade these references to class and instance methods and variables together and resulting in constructs like the one that appears in the sample program:

System.out.println()

Sum it Up

Class variables and class methods are associated with a class and occur once per class. Instance methods and variables occur once per instance of a class.


Previous | Next | Trail Map | Writing Java Programs | The Anatomy of a Java Application