TestClass.java
Select all
/* TestClass.java David Klick 2014-02-09 CIS 260 This program demonstrates some basic access modifier and class concepts. */ public class TestClass { // automatically extends Object static int x; // only one x, shared by all objects of TestClass int y; // each object of TestClass gets its own y variable public int a; // a is accessible to any other class private int b; // b is accessible only to TestClass objects protected int c; // c is accessible to TestClass objects, any // subclass objects, and any classes in the // same package final static double PI = 3.2; // innacurate constant declaration // of the above variables, only x will be automatically initialized (to 0) private void incXY() { // since this is an instance method, it has access to both // instance and static variables x++; y++; } public static void main(String[] args) { // this method only has access to the static members x = 7; // works // but "a = 17;" wouldn't work int y = 18; // we can set y to 18, but it is not the same y that // is the instance variable declared previously - // we just created a new one // we can't call incXY() directly since it is an instance // method (part of an individual object) and we are in a static // method which has no direct reference to an object // we can however create an object and use it to call incXY() TestClass t = new TestClass(); // creates a new one of us t.incXY(); // this works System.out.println("x=" + x + ", y=" + y + ", t.y =" + t.y); } } /* Output from sample run: x=8, y=18, t.y =1 */