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的好处:
多个对象,共享一份,节约内存。
本文通过对比非静态与静态变量的使用场景及内存图解,详细介绍了Java中静态static关键字的作用和优势,特别是如何通过静态变量实现多个对象间共享同一份数据以节省内存。
1449

被折叠的 条评论
为什么被折叠?



