掌握有无stctic修饰成员变量的用法、特点

package com.StaticDemo;

public class Student {
    //类变量也是静态变量
    static String name;

    //实例变量
也叫对象变量
    int age;
}
package com.StaticDemo;

public class Test {
    public static void main(String[] args) {
        //掌握有无stctic修饰成员变量的用法、特点
        /**类变量:有static,属于类,在计算机里只有一份,会被类的全部对象共享
         * 实例变量(对象的变量):无static修饰,属于每个对象的
         *
         * */
        //1.类变量的用法
        //类名.类变量(推荐)
        Student.name="袁华";

        //对象.类变量(不推荐)
        Student s1=new Student();
        s1.name="马冬梅";

        Student s2=new Student();
        s2.name="秋雅";

        System.out.println(s1.name);//秋雅
        System.out.println(Student.name);//秋雅

        //2.实例变量的用法
        //对象.实例变量
        s1.age=23;
        s2.age=18;
        System.out.println(s1.age);//23
        //   System.out.println(Student.age);//报错
    }
}

 

posted @ 2023-05-28 14:10  Karlshell  阅读(12)  评论(0)    收藏  举报