Created
September 2, 2013 05:28
-
-
Save akirad/6409462 to your computer and use it in GitHub Desktop.
These code are easy sample(test) for static field in Java.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package staticFieldTest; | |
public class Sub1 extends Base { | |
// Just extends Base. | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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