static关键字

static关键字

public class Student {
    private static int age=10;//静态的变量
    private double score=100;//非静态的变量
    
    public static void main(String[] args){
        Student s1 = new Student();

        System.out.println(Student.age);//静态变量,可以用类名调用,也可以用new的对象进行调用
        System.out.println(Student.score);//报错   为非静态的变量,不能用类名调用
        System.out.println(s1.age);
        System.out.println(s1.score);
    }
}

方法

public class Student {
    //非静态方法可以调用静态方法的东西
    //静态方法可以调用静态方法的东西
    public void run(){
        go();
    }
    public static void go(){
    }

    public static void main(String[] args) { 
        new Student().run();//先new在调
        //直接调或用类名调都行
        go();
        Student.go();
    }
}
//静态导入包
import static java.lang.Math.random;

public class Test {
    public static void main(String[] args) {
        System.out.println(random());//a随机
    }
}
posted @ 2021-07-21 15:50  valder-  阅读(30)  评论(0)    收藏  举报