Computer Science 252
Problem Solving with Java
Spring 2014, The College of Saint Rose
StaticStuff BlueJ Project
Click here to download a BlueJ project for StaticStuff.
StaticStuff Source Code
The Java source code for StaticStuff is below. Click on a file name to download it.
/*
* Example StaticStuff: demonstrating static vs. non-static
* variables and methods
*
* Jim Teresco, The College of Saint Rose, CSC 252, Spring 2014
*
* $Id: StaticStuff.java 2351 2014-05-01 01:51:25Z terescoj $
*/
public class StaticStuff {
// a class variable
private static int classVar;
// an instance variable
private int instanceVar;
// a constructor which will store the x parameter in classVar
// and the y parameter in instanceVar
public StaticStuff(int x, int y) {
classVar = x;
instanceVar = y;
}
// a toString method for this class
public String toString() {
return "classVar is " + classVar + ", instanceVar is " + instanceVar;
}
// the main method, which is the way to run
// this program
public static void main(String[] args) {
// I can access my class variable here, even in a
// static method
classVar = 10;
// But I can't access the instance variable
//instanceVar = 20;
// print out our class variable
System.out.println("classVar is " + classVar);
// so let's create an instance of this class
StaticStuff first = new StaticStuff(17, 23);
System.out.println("classVar is " + classVar);
System.out.println("first: " + first);
// and another instance of this class
StaticStuff second = new StaticStuff(12, 15);
System.out.println("classVar is " + classVar);
System.out.println("first: " + first);
System.out.println("second: " + second);
}
}