static 关键字是静态的意思,是Java中的一个修饰符,可以修饰成员方法,成员变量
被类的所有对象共享
是我们判断是否使用静态关键字的条件
随着类的加载而加载,优先于对象存在
对象需要类被加载后,才能创建
可以通过类名调用
也可以通过对象名调用
静态方法只能访问静态的成员
非静态方法可以访问静态的成员,也可以访问非静态的成员
静态方法中是没有this关键字
示例代码
xxxxxxxxxx
package com.itheima.test;
public class Student {
String name;
int age;
static String school;
/*
静态随着类的加载而加载, 优先于对象存在
非静态需要在创建对象之后,才可以进行使用
1. 静态方法中, 只能访问静态成员(成员变量, 成员方法)
2. 非静态方法中, 可以使用静态成员, 也可以使用非静态成员
3. 静态方法中, 没有this关键字
*/
public void show() {
System.out.println(name + "..." + age + "..." + school);
}
public static void method(){
// this: 当前对象的引用
// this需要在创建对象之后, 才会存在, 静态存在的时候, 对象可能还没有被创建
// this.name = "张三";
System.out.println(school);
}
}
xxxxxxxxxx
package com.itheima.test;
public class Test1Static {
/*
1. 被static修饰的成员, 会被该类的所有对象所[共享]
2. 被static修饰的成员, 会随着类的加载而加载, 优先于对象存在
3. 多了一种调用方式, 可以通过类名.进行调用
*/
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();
}
}