static关键字及内存图

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);
        }
    }
    

    static关键字及内存图_第1张图片

  • 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关键字及内存图_第2张图片

静态static的好处:

多个对象,共享一份,节约内存。

你可能感兴趣的:(面向对象)