Static variables and methods

public class SomeObject {
    // A static variable:
    private static int sharedData = 1;
    // An instance variable
    private int individualData;

    public SomeObject(int data) {
	individualData = data;
    }

    public void print() {
	System.out.println("Individual data = " + individualData + 
			   " Shared data " + sharedData);
    }

    public void changeIndividual(int d) {
	individualData += d;
    }

    // This is a static method
    public static void changeShared(int d) {
	sharedData += d;
    }
}


public class TestStatic {
    public static void main(String [] args) {
	SomeObject obj1 = new SomeObject(2);
	SomeObject obj2 = new SomeObject(4);
	SomeObject obj3 = new SomeObject(6);

	// changing instance variables:
	obj1.changeIndividual(3);
	obj2.changeIndividual(7);

	// changing static variables:
	obj1.changeShared(1);
	obj3.changeShared(2);
	
	obj1.print();
	obj2.print();
	obj3.print();	

	// Calling a static method on a class itself
	SomeObject.changeShared(-10);
	
	obj1.print();
	obj2.print();
	obj3.print();	
    }
}

This is an example from CSci 2101 course.

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.