1+ /*
2+ * @由于个人水平有限, 难免有些错误, 还请指点:
3+ * @Author: cpu_code
4+ * @Date: 2020-09-12 23:28:50
5+ * @LastEditTime: 2020-09-12 23:29:24
6+ * @FilePath: \java\javaAPI\Static\class_method.java
7+ * @Gitee: [https://gitee.com/cpu_code](https://gitee.com/cpu_code)
8+ * @Github: [https://github.com/CPU-Code](https://github.com/CPU-Code)
9+ * @CSDN: [https://blog.csdn.net/qq_44226094](https://blog.csdn.net/qq_44226094)
10+ * @Gitbook: [https://923992029.gitbook.io/cpucode/](https://923992029.gitbook.io/cpucode/)
11+ */
12+ package javaAPI .Static ;
13+
14+ public class class_method {
15+ public static void main (String [] args ){
16+ Student s1 = new Student ("cpucode" , 22 );
17+ Student s2 = new Student ("cpu" , 21 );
18+
19+ s1 .show ();
20+ s2 .show ();
21+
22+ // 访问类变量
23+ System .out .println (Student .numberOfStudent );
24+
25+ // 调用静态方法
26+ Student .showNum ();
27+ }
28+ }
29+
30+ class Student {
31+ private String name ;
32+ private int age ;
33+
34+ // 学生的id
35+ private int sid ;
36+ // 类变量,记录学生数量,分配学号
37+ public static int numberOfStudent = 0 ;
38+
39+ public Student (String name , int age ){
40+ this .name = name ;
41+ this .age = age ;
42+ // 通过 numberOfStudent 给学生分配学号
43+ this .sid = ++numberOfStudent ;
44+ }
45+
46+ // 打印属性值
47+ public void show (){
48+ System .out .println ("Student: name = " + name + ", age = " + age + ", sid = " + sid );
49+ }
50+
51+ public static void showNum () {
52+ System .out .println ("num == " + numberOfStudent );
53+ }
54+ }
55+
56+ /*
57+ Student: name = cpucode, age = 22, sid = 1
58+ Student: name = cpu, age = 21, sid = 2
59+ 2
60+ num == 2
61+ */
0 commit comments