首页 > 其他 > 详细

Static详解

时间:2020-07-13 18:20:46      阅读:49      评论:0      收藏:0      [点我收藏+]

Static详解

//static : 和类一起加载的
public class Student {
    private static int age; //静态的变量 多线程!
    private double score;   //非静态的变量

    public void run(){//非静态方法可以调用所以静态的方法
        go();

    }
    public static void go(){

    }

    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);

        //static可以扩大使用范围
        new Student().run();
        go();

    }
}

测试看输出结果

public class Person {

    //2: 赋初始值
    {
        System.out.println("匿名代码块");
        //代码块(匿名代码块) 创建这个对象自己的就创建了(在构造器之前)
    }

    //1
    static {
        System.out.println("静态代码块");
        //静态代码块(加载一些初始的东西),类加载就执行了,永久只执行一次
    }

    //3
    public Person(){
        System.out.println("构造方法");
    }

    public static void main(String[] args) {
        Person person1 = new Person();
        System.out.println("============");
        Person person2 = new Person();
    }
}

技术分享图片

java静态导入包

//静态导入包
import static java.lang.Math.random;
import static java.lang.Math.PI;


public class Test {

    public static void main(String[] args) {
        System.out.println(random());
        System.out.println(PI);
    }
}

Static详解

原文:https://www.cnblogs.com/helloxiaolu/p/13294873.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!