More on Classes

Class vs Instance Members

Class members are fields and methods that belong to the class, rather than to an instance of the class.

static Keyword

The static keyword is used to create the fields and methods without having to make an instance of the class.

Class Variables / Static Fields

Static fields only exist in one copy. The static fields belong to the class not to an instance of the class. The static fields exist even without creating an object since they belong to the class itself. Every instance of the class shares a class variable, which is in one fixed location in memory.

Creating Class Variables

Class variables are created by marking them with the static keyword modifier.

public class Socket {
    String id;
    //class variable
    static String url = "http://chat.peruzal.co.za";
}

All socket objects will have the same url field, since been marked static.

Accessing Static Fields

To access class fields you use the class name followed by the dot operator. To access the url field of the Socket class, we can do the following :

String apiUrl = Socket.url;

Notice we are using the class name not an instance of the class. You can also access the static fields using an object reference but this is discouraged and misleading.

Socket socket = new Socket();
String apiUrl = socket.url;

Here is an example of accessing PI from the built-in Math class. Notice we did not instantiate the Math class object in order to access the PI class field. PI is declared as a static field.

double radius = 5.0;
double area = Math.PI * radius * radius;

Class Methods / Static Methods

Static methods are created by marking them with the static keyword modifier. Static methods are invoked with the class name followed with the dot operator. There is no need to create an instance of the class to access them.

The Math class have all its methods implemented as static. There's no need to create an instance of the Math class to perform math operations.

// raise to 2 to the power of 3
double result = Math.pow(2, 3);

Another common operation is printing and getting input to and from the terminal with System class. The System class contains the out, err and in static fields. The following will print the string Hello World to the console output.

 System.out.println("Hello World");

Since the the println method is overloaded we can pass it different types and it will print them to the console.

double result = Math.pow(2, 3);
System.out.println(result);

We can get the current time as a unix timestamp using the static method currentTimeMillis as follows :

long unixTimestamp = System.currentTimeMillis();

We could also hint the program to perform a garbage collection. Note this is not guranteed to run immediately.

System.gc();

The Arrays class in the java.util package also contains various static methods for manipulating arrays.

We can perform a sort operation on an array by calling the static sort method as follows :

int[] scores = {10, 50, 49, 78, 100 };
Arrays.sort(scores);
System.out.println(Arrays.toString(scores));

Result : [10, 49, 50, 78, 100]

Constants

Constants are fields with values that do not change as opposed to variables that are constantly changing. Constants are defined by combining the the static modifier keyword in combination with the final modifier keyword.

In the Socket class, we can define various events of the socket as constants.

public static final String EVENT_CONNECT = "connect";
public static final String EVENT_DISCONNECT = "disconnect";
public static final String EVENT_ERROR = "error";

We also marked the constant fields as public so they will be available to the world as well.

Static Method Rules

Not all combinations of instance and static fields and methods are allowed:

  1. Instance methods can access instance variables and instance methods directly
  2. Instance methods can access static variables and methods directly
  3. Static methods can assess static fields and other static methods directly
  4. Static methods cannot access instance variables methods directly - they must use an object reference.
  5. Static methods can not use the this keyword as there is no instance for this to refer to.

Java Command Line Programs

Now you can understand how the Java command line programs can run without creating new objects of themselves. Here is a HelloWorld java program.

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello World");
    }
}

Output : Hello World

The entry point into the program is the main method. There's no need to create an object of the Main class. main is declared as static, the the Java Virtual Machine can invoke the main method without creating an object of the Main class.

The main method is also declared as public so its available to the world. void, means it does not return any value, and it takes in a comma separated list of String parameters.

results matching ""

    No results matching ""