Java基础-静态变量(类变量)

package com.hspedu.static_;

public class Course374 {
    public static void main(String[] args) {
        // 类变量快速入门

        // 这样使用静态static变量不规范
        Child child1 = new Child("白骨精");
        child1.join();
        child1.count++;
        Child child2 = new Child("狐狸精");
        child2.join();
        child2.count++;
        Child child3 = new Child("蜘蛛精");
        child3.join();
        child3.count++;

        // 类变量可以通过 类名.变量名 访问
        System.out.println("现在共有:" + Child.count + " 个加入了");
        System.out.println(child1.count);
        System.out.println(child2.count);
        System.out.println(child3.count);
    }
}

class Child {

    private String name;

    // 定义一个类变量(静态变量),static
    // 所有的对象都可以共享这个属性
    public static int count;    // int默认值是0

    public Child(String name) {
        this.name = name;
    }

    public void join() {
        System.out.println(this.name + "加入了..");
    }
}

 

package com.hspedu.static_;

public class Course375 {
    public static void main(String[] args) {
        // 类变量/静态变量的内存分析

        /*
         *   1、child1、child2、child3对象当中都存放了一个地址,
         *      这个地址指向了count存放的位置(可能是堆空间、可能是方法区的静态域)
         *      静态变量不管是存放在哪里,不影响其使用方式,所有对象均指向一个位置
         *   2、方法区有个空间叫:静态域
         *   3、静态变量的存放位置和jdk的版本有关,一般jdk7之前是在方法区中,jdk8以后是在堆空间
         *   4、类第一次在加载的时候,方法区会生成类信息,同时也会在堆空间上生成一个对应的Class对象(反射部分)
         *
         * */
        Child child1 = new Child("Tom");
        Child child2 = new Child("Jack");
        Child child3 = new Child("Mary");

    }
}


class Child {

    private String name;

    public static int count = 0;

    public Child(String name) {
        this.name = name;
    }

    public void join() {
        System.out.println(this.name + "加入了..");
    }
}
package com.hspedu.static_;

public class Course377 {
    public static void main(String[] args) {
        // 类变量(静态变量)访问细节

        /*
         * 1、使用静态变量的需求:所有对象共享一个属性值(例如统计)
         * 2、静态变量和实例变量区别:静态变量是所有对象共享、实例变量是每个对象独有
         * 3、访问方式:类名/对象.变量名(前提是满足访问权限)
         * 4、实例变量不能通过类.变量名的方式访问
         * 5、类加载了,不需要实例化也可以使用静态变量
         * 6、静态变量的声明周期是随着类的加载开始,类的消亡而销毁
         * */

        A a = new A();
        System.out.println(A.n2);
        // System.out.println(A.n1);

        System.out.println(B.address);

    }
}

class A {

    // 类变量/静态变量
    public static String name = "韩顺平教育";

    // 普通属性/普通成员变量/非静态变量/实例变量
    private int num = 10;

    public int n1 = 100;    // 不能通过A.n1访问

    public static int n2 = 200;
}

class B {
    public static String address = "北京";
}

 

posted @ 2022-03-14 15:17  柯南同学  阅读(761)  评论(0编辑  收藏  举报