static关键字详解

注意

通过final修饰的类,它就不能被继承,没有子类

 

举例

Student.score会报错

 

代码

//Java-零基础学习/src/oop/demo07/Student
package oop.demo07;

import oop.demo06.Person;

//static
public class Student extends Person {

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

       new Student().run();
       Student.go();
       go();
  }
}
//Java-零基础学习/src/oop/demo07/Person
package oop.demo07;

public final class Person {

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

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

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

   public static void main(String[] args) {
       Person person = new Person();
       System.out.println("==============");
  }
}
//Java-零基础学习/src/oop/demo07/Test
package oop.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(random());
       System.out.println(PI);
  }
}
 
posted @ 2024-01-13 22:30  poiuyjoey  阅读(17)  评论(0)    收藏  举报