2022.3.29 static

静态变量

 1 package com.oop.demo09;
 2  3  //static
 4  public class Student {
 5      private static int age;//静态变量 类变量 通常使用类名调用
 6      private double score;//非静态变量
 7  8      public static void main(String[] args) {
 9          Student student = new Student();
10          //通过对象名.变量名调用
11          System.out.println(student.score);
12          System.out.println(student.age);
13 14          //通过类名.变量名调用         所有也叫类变量
15          System.out.println(Student.age);
16          //System.out.println(Student.score);非静态变量不可以通过类名调用
17      }
18  }

静态方法

 1  package com.oop.demo09;
 2  3  import sun.misc.PostVMInitHook;
 4  5  //static
 6  public class Student {
 7      //非静态方法
 8      public void run(){
 9 10      }
11      //静态方法
12      public static void go(){
13 14      }
15      public static void main(String[] args) {
16          //静态方法通过类名.方法名调用,(调用另一个类中的静态方法同理)
17          Student.go();
18 19          //静态方法还可以直接调用:因为这个静态方法在这个类中
20          go();
21 22          //非静态方法,无法通过类名.方法名调用,通过对象名.方法名调用
23          Student student = new Student();//实例化这个类new
24          student.run();
25          new Student().run();//还可以这样直接调用
26 27          student.go();//静态方法也可以通过对象名.方法名调用
28 29      }
30 31  }

 1   package com.oop;
 2  3   public class Demo01 {
 4       public static void main(String[] args) {
 5           //静态方法static,通过类名.方法名调用(调用另一个类中的方法同理)
 6           Student.say();
 7  8           Student student = new Student();
 9           student.say1();
10 11           new Student().say1();
12       }
13       //两个非静态方法可以调用
14       public void a() {
15           b();
16       }
17       public void b() {
18       }
19       //两个静态方法可以调用
20       public static void a1() {
21           b1();
22       }
23       public static void b1() {
24       }
25 26       //一个非静态一个静态可以调用
27       public void a3() {
28           b3();
29       }
30       public static void b3() {
31       }
32 33       /*一个静态一个非静态不可以调用
34       public static void a2() {//和类一起加载
35           b2();
36       }
37       public void b2() {//实例化之后才存在
38       }*/
39   }
 
 1   package com.oop;
 2  3   //学生类
 4   public class Student {
 5       //静态方法
 6       public static void say() {
 7           System.out.println("学生说话");
 8       }
 9       //非静态方法
10       public void say1() {
11           System.out.println("学生又说话");
12       }
13   }

静态导入包

 1  package com.oop.demo09;
 2  3  //import java.lang.Math;一般这么导入类就行了
 4  5  //静态导入包                 直接导入方法  作为了解
 6  import static java.lang.Math.random;
 7  import static java.lang.Math.PI;//导入PI
 8  9  public class Test {
10      public static void main(String[] args) {
11          System.out.println(random());//不用写Math.random();
12          System.out.println(PI);
13      }
14  }
posted @ 2022-03-29 15:49  暴躁C语言  阅读(44)  评论(0)    收藏  举报