1 package day1.yppah04.p6;
2
3 /*
4 4.6 static
5
6 static的概念
7 static关键字是静态的意思,可以修饰【成员方法】,【成员变量】
8 static修饰的特点
9 1. 被类的所有对象共享,这也是我们判断是否使用静态关键字的条件
10 2. 可以通过类名调用当然,也可以通过对象名调用【推荐使用类名调用】
11 */
12
13 public class StudentDemo {
14 public static void main(String[] args) {
15 //school被static修饰前
16 /*Student s1 = new Student();
17 s1.name = "tom";
18 s1.age = 20;
19 s1.school = "qdu";
20 s1.show();
21
22 Student s2 = new Student();
23 s2.name = "amy";
24 s2.age = 22;
25 s2.school = "qdu";
26 s2.show();*/
27
28 //school被static修饰后
29 /*Student s1 = new Student();
30 s1.name = "tom";
31 s1.age = 20;
32 s1.school = "qdu"; //school变为共享
33 s1.show();
34
35 Student s2 = new Student();
36 s2.name = "amy";
37 s2.age = 22;
38 // s2.school = "qdu";
39 s2.show();*/
40
41 Student.school = "qdu"; //建议这样直接用类名访问
42 Student s1 = new Student();
43 s1.name = "tom";
44 s1.age = 20;
45 // s1.school = "qdu";
46 s1.show();
47
48 Student s2 = new Student();
49 s2.name = "amy";
50 s2.age = 22;
51 // s2.school = "qdu";
52 s2.show();
53 }
54 }
1 package day1.yppah04.p6;
2
3 public class Student {
4
5 public String name;
6 public int age;
7 public static String school;
8
9 public void show(){
10 System.out.println(name + "," + age + "," + school);
11 }
12
13 }
1 package day1.yppah04.p7;
2
3 /*
4 4.7 static访问特点
5
6 非静态的成员方法
7 能访问静态的成员变量
8 能访问非静态的成员变量
9 能访问静态的成员方法
10 能访问非静态的成员方法
11 静态的成员方法
12 能访问静态的成员变量
13 能访问静态的成员方法
14 总结成一句话就是:
15 静态成员方法只能访问静态成员
16 */
17
18 public class Student {
19
20 private String name = "tom"; //非静态成员变量
21 private static String school = "qdu"; //静态成员变量
22
23 public void show1(){ //非静态成员方法
24
25 }
26
27 public void show2(){ //非静态成员方法
28 System.out.println(name);
29 System.out.println(school);
30 show1();
31 show3();
32 }
33
34 public static void show3(){ //静态成员方法
35
36 }
37
38 public static void show4(){ //静态成员方法
39 // System.out.println(name); //error
40 System.out.println(school);
41 // show1(); //error
42 show3();
43 }
44
45 }