JAVA---static关键字学习

static关键字学习

package com.oop.demo07;
//static加在方法上是静态方法,加在属性上静态属性
public class Student {
  //静态变量可以直接类类名.变量名来使用
  //非静态不可以这么使用
  //非静态方法可以new 类名().方法名();来使用
  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(s1.age);
      System.out.println(s1.score);
      System.out.println("==");
      new Student().run();
  }
  public void run(){
      System.out.println("====================");
      go();
  }
  public static void go(){
      System.out.println("==========");
  }
}

package com.oop.demo07;

public class Person {
  {
      //代码块(匿名代码块)不建议这么写
      //程序在执行的时候不能调用,匿名代码块程序在创建这个
      //对象时就自动创建了,在构造器之前
      System.out.println("匿名代码块");//2
  }
  static{
      //静态代码块,可以加载一些初始化的东西
      //跟类一加载就直接执行,永久只执行一次
      System.out.println("静态代码块");//1
  }

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

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

package com.oop.demo07;
//导入静态包
import static java.lang.Math.random;
public class Test {
  public static void main(String[] args) {
      System.out.println(random());
  }
}
 
posted @ 2022-10-04 17:53  学JAVA的旅行者  阅读(22)  评论(0)    收藏  举报