Skip to content

Instantly share code, notes, and snippets.

@akirad
Created September 2, 2013 05:28
Show Gist options
  • Save akirad/6409462 to your computer and use it in GitHub Desktop.
Save akirad/6409462 to your computer and use it in GitHub Desktop.
These code are easy sample(test) for static field in Java.
package staticFieldTest;
public abstract class Base {
public static int staticCounter = 0;
public int NonStaticCounter = 0;
public void countUp(){
staticCounter++;
NonStaticCounter++;
}
public void showCounter(){
System.out.println("staticCounter: " + staticCounter);
System.out.println("NonStaticCounter: " + NonStaticCounter);
}
}
package staticFieldTest;
public class Main {
public static void main(String[] args) {
Base sub1 = new Sub1();
Base sub2 = new Sub2();
sub1.countUp();
sub2.countUp();
sub1.showCounter();
sub2.showCounter();
// Result:
// - staticCounter: 2
// - NonStaticCounter: 1
// "staticCounter" is shared even if it is in base class and extended to both sub1 and sub2.
}
}
package staticFieldTest;
public class Sub1 extends Base {
// Just extends Base.
}
package staticFieldTest;
public class Sub2 extends Base {
// Just extends Base.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment