static关键字详解

素颜马尾好姑娘i 2023-10-01 13:00 39阅读 0赞

1、知识点都在代码注释中,便于理解

  1. `package oop.Demon09;
  2. import oop.Demon05.Students;
  3. public class Student {
  4. private static int age=10;//静态变量 多线程
  5. private double score;//非静态变量
  6. public void run(){
  7. System.out.println("run");
  8. //非静态方法 可以直接访问 该类中的静态方法
  9. go();
  10. }
  11. public static void go(){
  12. System.out.println("go");
  13. //但是 静态方法 只能调用静态方法 因为静态方法 跟类一块加载,加载之前 都没有非静态方法
  14. }
  15. public static void main(String[] args) {
  16. Student s1 = new Student();
  17. // s1.age 可以调用
  18. // Student.age 也可以 用类名.属性名 调用
  19. System.out.println(Student.age);
  20. // System.out.println(Student.score);报错, 类名.属性名 调用 只能用在static类型变量
  21. System.out.println(s1.age);
  22. System.out.println(s1.score);
  23. new Student().run(); //非静态方法,只能先new,在调用
  24. Student.go(); go();//静态方法,直接调用, 类名。方法名 或者 直接 方法名
  25. }
  26. }

2、

  1. package oop.Demon09;
  2. public class Person {
  3. //2、对象一创建,就先走匿名代码块,再走构造方法 作用: 赋初值
  4. {
  5. //代码块 (匿名代码块)
  6. System.out.println("匿名代码块");
  7. }
  8. //1、只执行一次
  9. static {
  10. //静态代码块 类一经加载 就永久执行一次
  11. System.out.println("静态代码块");
  12. }
  13. //3、对象一创建,就先走匿名代码块,再走构造方法
  14. public Person() {
  15. System.out.println("构造方法");
  16. }
  17. public static void main(String[] args) {
  18. Person person1 = new Person();
  19. //静态代码块
  20. //匿名代码块
  21. //构造方法
  22. System.out.println("=========================");
  23. Person person2 = new Person();
  24. //匿名代码块
  25. //构造方法
  26. }
  27. }

3、

  1. package oop.Demon09;
  2. //静态导入包
  3. import static java.lang.Math.random;
  4. import static java.lang.Math.PI;
  5. public class Test {
  6. public static void main(String[] args) {
  7. System.out.println(Math.random()); //产生一个随机数 每次都不一样
  8. System.out.println(random()); //可以直接 用方法名字
  9. System.out.println(PI);
  10. }
  11. }

4、通过 final修饰的类 不能被继承

发表评论

表情:
评论列表 (有 0 条评论,39人围观)

还没有评论,来说两句吧...

相关阅读

    相关 static关键字用法详解

    在程序中使用static 变量 1. 局部变量 普通局部变量是再熟悉不过的变量了,在任何一个函数内部定义的变量(不加static修饰符)都属于这个范畴。编译

    相关 详解关键字static,const

    static static修饰局部变量 static修饰局部变量用于修改变量的存储位置,从自动变量修改为静态变量(在静态区开辟空间,不在栈上开辟),但变量的链接