面向对象——补充:static

static

  • 静态变量可以直接用类名访问,也称类变量
  • 静态变量(或方法)对于类,能被所有对象(实例)共享、
public class Student {
    private static int age;
    private double score;

    public static void main(String[] args) {
        Student s1 = new Student();
        System.out.println(Student.age);//静态变量对于类,被所有对象(实例)共享
        System.out.println(Student.score);//报错
  • 静态变量可以直接调用,但是非静态变量不可以直接调用

image

  • 静态区代码加载类时一起被初始化,最早执行且只执行一次(第一次new),而匿名代码块一般用于赋初始值。
  • 拓展:静态导入包
//静态导入包
import static java.lang.Math.random;
public class Application {    
    public static void main(String[] args) {        
        //第一种随机数,不用导包        
        System.out.println(Math.random()); 
        //0.7562202902634543        
        //第二种随机数,静态导入包        
        System.out.println(random()); 
        //0.5391606223844663    
    }
}
posted @ 2022-08-20 09:44  Fred不想做咸鱼  阅读(35)  评论(0)    收藏  举报