static修饰符

static修饰符

1.概念
静态的意思,可修饰成员方法、成员变量。
2.static修饰的特点
(1)被类的所有对象共享(我们判断是否使用它的关键)
(2)可以通过类名直接调用。
(3)被static修饰的成员会随着类的加载而加载,会优于对象先存在。

public class TestStatic {
    public static void main(String[] args) {
        Student.school ="传智专修学院";
        Student student = new Student();
        student.school ="大草原学院";
        student.name ="张三";
        student.age =20;
        student.show();
        show1();
    }
    private static void show1(){
        System.out.println(Student.school);
    }
}

 class Student {
    public String name;
    public int age;
    public static String school ;
    //静态方法中只能访问静态成员(成员变量,成员方法)
    /*静态随着类的加载而加载优于对象存在*/
    public void show(){
        System.out.println(name+".."+age+".."+school);
    }
}
------------------------------------
打印结果
张三..20..大草原学院
大草原学院
------------------------------------

3.static的访问特点
(1)非静态的成员方法:可访问【静态和非静态的成员变量和成员方法】
(2)静态方法中没有this关键字
(3)静态成员方法只能访问静态成员

4.工具类
由静态方法组成的类称为工具类

public class TestUtil {
    public static void main(String[] args) {
        System.out.println(Util.getMax());
        System.out.println(Util.getMin());
        System.out.println(Util.getSum());
    }
}

//类中全部是静态的方法则称作为工具类
//其他类可以通过类名直接调用
class Util {
    private static int[] arr = {1, 2, 3, 4, 5};
    public static int getMax() {
        int max = arr[0];
        for (int i = 0; i < arr.length; i++) {
            if (max < arr[i]) {
                max = arr[i];
            }
        }
        return max;
    }
    public static int getMin() {
        int min = arr[0];
        for (int i = 0; i < arr.length; i++) {
            if (min > arr[i]) {
                min = arr[i];
            }
        }
        return min;
    }
    public static int getSum() {
        int sum =0;
        for (int i = 0; i < arr.length; i++) {
            sum += arr[i];
        }
        return sum;
    }
}
-------------------------------------
打印结果
5
1
15
-------------------------------------
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陪雨岁岁年年

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值