Java学习-面向对象06静态和非静态(详解static关键字)

静态和非静态(详解static关键字)

代码示例

Student.java

package com.oop.www.demo07;

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);
//        System.out.println(s1.age);
//        System.out.println(s1.score);

        new Student().run();
        Student.go();
        go();
        //报错,需要实例化对象才能调用非静态方法
        //run();
    }



    //非静态
    public void run(){
        go();

    }
    
    //静态
    public static void go(){


    }


}

Person.java

package com.oop.www.demo07;

public class Person {
    {
        //匿名代码块(2):初始化赋值
        System.out.println("匿名代码块");
    }

    static {
        //静态代码块(1):只执行一次
        System.out.println("静态代码块");
    }

    public Person() {
        //构造方法(3):创建对象时执行,初始化赋值
        System.out.println("构造方法");
    }

    public static void main(String[] args) {
        Person p1 = new Person();
        System.out.println("===============");
        /*第二次只是输出:
        匿名代码块
        构造方法
        因此得出结论:静态代码块只执行一次,构造方法每次执行都会执行,匿名代码块每次执行都会执行
        */
        Person p2 = new Person();
    }
}

Test.java

package com.oop.www.demo07;
//静态导入包
import static java.lang.Math.random;
import static java.lang.Math.PI;

public class Test {
    public static void main(String[] args) {
        //System.out.println(Math.random());
        System.out.println(random());
        System.out.println(PI);
    }
}
posted on 2025-06-29 15:44  burgess0x  阅读(6)  评论(0)    收藏  举报