java類靜態方法測試
阿新 • • 發佈:2019-02-06
靜態方法是在new之前就已經載入到記憶體地址中了,再次new物件時候這些靜態屬性或者靜態方法不會再分配新的記憶體地址了,這些靜態屬性或者靜態方法在多個物件中是共用的。
結果:public class Common { private static String test = "123"; private String test1 = "456"; public static String getTest() { return test; } public static void setTest(String test) { Common.test = test; } public String getTest1() { return test1; } public void setTest1(String test1) { this.test1 = test1; } } /*************test*************/ System.out.println("Common test = "+Common.getTest()); Common.setTest("abc"); System.out.println("Common test = "+Common.getTest()); Common com = new Common(); Common com1 = new Common(); System.out.println("------------------------------"); System.out.println("com test = "+com.getTest()); System.out.println("com1 test = "+com1.getTest()); System.out.println("com test1 = "+com.getTest1()); System.out.println("com1 test1 = "+com1.getTest1()); com.setTest("cccccccccc"); com.setTest1("dddddddddd"); System.out.println("------------------------------"); System.out.println("com test = "+com.getTest()); System.out.println("com1 test = "+com1.getTest()); System.out.println("com test1 = "+com.getTest1()); System.out.println("com1 test1 = "+com1.getTest1()); System.out.println("Common test = "+Common.getTest());
Common test = 123
Common test = abc
------------------------------
com test = abc
com1 test = abc
com test1 = 456
com1 test1 = 456
------------------------------
com test = cccccccccc
com1 test = cccccccccc
com test1 = dddddddddd
com1 test1 = 456
Common test = cccccccccc