static 关键字是静态的意思,是Java中的一个修饰符,可以修饰成员方法,成员变量
2.static修饰的特点-
被类的所有对象共享, 是我们判断是否使用静态关键字的条件
-
随着类的加载而加载,优先于对象存在
对象需要类被加载后,才能创建
-
可以通过类名调用
也可以通过对象名调用
-
静态方法只能访问静态的成员
-
非静态方法可以访问静态的成员,也可以访问非静态的成员
-
静态方法中是没有this关键字
-
示例代码
- Student类
package com.itheima.test; public class Student { String name; int age; static String school; public void show() { System.out.println(name + "..." + age + "..." + school); } public static void method(){ // this: 当前对象的引用 // this需要在创建对象之后, 才会存在, 静态存在的时候, 对象可能还没有被创建 // this.name = "张三"; System.out.println(school); } }- 测试类
package com.itheima.test; public class Test1Static { public static void main(String[] args) { Student.school = "啦啦啦学院"; Student stu1 = new Student(); stu1.name = "张三"; stu1.age = 23; //stu1.school = "啦啦啦学院"; stu1.show(); Student stu2 = new Student(); stu2.show(); //调用静态方法 Student.method(); } }



