static关键字及内存图
A:没有加静态static的代码示例及内存图解
class Demo1_Static{ public static void main(String[] args){ Person p1 = new Person(); p1.name = "苍老师"; p1.country = "日本"; p1.speak(); Person p2 = new Person(); p2.name = "小泽老师"; p2.country = "日本"; p2.speak(); } } class Person{ String name; String country; public void speak(){ System.out.println(name + "..." + country); } }
B:添加静态static的代码示例及内存图解
class Demo1_Static{ public static void main(String[] args){ Person p1 = new Person(); p1.name = "苍老师"; p1.country = "日本"; Person p2 = new Person(); p2.name = "小泽老师"; p1.speak(); p2.speak(); } } class Person{ String name; static String country; public void speak(){ System.out.println(name + "..." + country); } }
静态static的好处:
多个对象,共享一份,节约内存。