Java_面向对象高级一-static修饰成员变量

static修饰成员变量

static

  • 叫静态,可以修饰成员变量,成员方法
成员变量按照有无static修饰,分为两种:
- 类变量:有static修饰,属于类,在计算机中只有一份,会被类和类的全部对象共享
		- 类变量的访问方式:
			方式一:类名.类变量
//        用法一:类名.变量名(推荐)
        Student.name = "枫";
			方式二:对象.类变量
//        用法二:对象名.变量名(不推荐)
        Student student = new Student();
        student.name = "昱";
- 实例变量(对象的变量):无static修饰,属于每个对象的,每个对象都有一份,只能用对象访问
		- 实例变量的访问方式:
			方式一:对象.实例变量
//        用法:对象名.变量名
        student.age = 18;

有无static修饰的成员变量完整例子

package com.zzfeng.d1_staticdemo;

public class Test {
    public static void main(String[] args) {
//掌握有无static修饰成员变量的用法,特点
//        1.类变量的用法
//        用法一:类名.变量名(推荐)
        Student.name = "枫";
//        用法二:对象名.变量名(不推荐)
        Student student = new Student();
        student.name = "昱";

        Student student1 = new Student();
        student1.name = "彭";

        System.out.println(student.name);
        System.out.println(student1.name);
//        static修饰的,类变量被共享,所以是一样的内容

//        2.实例变量的用法
//        用法:对象名.变量名
        student.age = 18;
        student1.age = 19;
        System.out.println(student.age);
        System.out.println(student1.age);
//        无static修饰,实例变量,内容不同
    }
}

package com.zzfeng.d1_staticdemo;

public class Student {
    //    类变量(所有类公用这一个变量)
    static String name;
    //    实例变量(对象的变量)
    int age;
}

static修饰成员变量的应用场景

  • 在开发中,如果某个数据只需要一份,且希望能够被共享(访问、修改),则该数据可以定义成类变量来实现
  • 案例:
    • 系统启动后,要求用户类可以记住自己创建了多少个用户对象
    • 代码:
      测试类
package com.zzfeng.d1_staticdemo;

public class UserTest {
    public static void main(String[] args) {
//        类变量应用场景
        User user = new User();
        User user1 = new User();
        User user2 = new User();
        User user3 = new User();

        System.out.println(User.number);
    }
}

	  类变量:
package com.zzfeng.d1_staticdemo;

public class User {
    //    类变量(所有类公用这一个变量)
    public static int number;

    public User() {
//        在同一个类中访问自己的类变量可不写类名
        number++;
    }
}

访问自己类中的类变量,可省略类名?

  • 自己的类中可以省略类名,但在某个类中访问其它类中的类变量,必须带类名访问
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值