Static attributes and methods in Java

From Knowledge Kitchen
Jump to navigation Jump to search

Static attributes and methods belong to the class as a whole. Non-static attributes and methods belong to any given object of the class.

Example of a static attribute

For example, image a class representing a Point in Cartesian space, as follows:

package edu.nyu.cs.fb1258;

public class Point {
	//some properties 
	public int x = 0;
	public int y = 0;
	public static int z = 0; //note that z is static

	//a convenient method for getting the String representation of a Point object
	public String toString() {
		return "A point object positioned at " + x + ", " + y + ", " + z;


Now, imagine code that instantiates a few Point objects:

package edu.nyu.cs.fb1258;

public class MakeSomePoints {

	public static void main(String[] args) {
		//instantiate a point object
		Point p1 = new Point();
		p1.x = 10;
		p1.y = 10;
		p1.z = 10; //since z is static, all Point objects have z = 10 as a result of this change

		//instantiate another point object
		Point p2 = new Point();
		//print out the values in both Point objects... note that p2 has z = 10
		System.out.println("p1: " + p1);
		System.out.println("p2: " + p2);



The output of this program would be:

p1: A point object positioned at 10, 10, 10
p2: A point object positioned at 0, 0, 10

Note that p2 has the value 10 in its z property.


In this example, changing p1's z value also changes p2's z value. That is because z does not belong to p1 or p2, but rather is static, which means it belongs to the class as a whole. All instances of the class refer to the same z value - changing it for one object changes it for all objects.

Clarity in code

Because z belongs to the class as a whole, it is misleading to write a statement in a way that suggests it belongs to one specific object, such as:

		p1.z = 10; //this statement suggests that z is a property that belongs to p1, which isn't true

A better way of writing that line would have been:

		Point.z = 10; //this clearly shows that z belongs to the class as a whole

Example of a static method

The same concept applies to static methods - they belong to the class as a whole, not any one object.

  • For this reason, you cannot use the keyword 'this' within a static method.

What links here