static修饰类中的某个成员 ,则这个成员是一个类属性/类方法,与类相关。
如果不加static,则这个成员是一个实例属性/实例方法,与对象/实例相关
1.修饰属性
static修饰的成员变量叫静态变量,属于类,不属于对象,在内存中的方法区所存储。
2.修饰方法
静态方法,属于类,不属于对象,调用静态方法,可以直接通过方法名来调用,也可以 类名.方法名来调用
在静态方法中不能访问非静态方法和非静态成员变量,this和super也不能再静态方法中使用,因为this和super都与实例相关。
class Person {
public int age;//实例变量 存放在对象内
public String name;//实例变量
public String sex;//实例变量
public static int count;//类变量也叫静态变量,编译时已经产生,属于类本身,且只有一份。
存放在方法区
public final int SIZE = 10;//被final修饰的叫常量,也属于对象。 被final修饰,后续不可
更改
public static final int COUNT = 99;//静态的常量,属于类本身,只有一份 被final修
饰,后续不可更改
//实例成员函数
public void eat() {
int a = 10;//局部变量
System.out.println("eat()!");
}
//实例成员函数
public void sleep() {
System.out.println("sleep()!");
}
//静态成员函数
public static void staticTest(){
//不能访问非静态成员
//sex = "man"; error
System.out.println("StaticTest()");
}
}
public class Main{
public static void main(String[] args) {
//产生对象 实例化对象
Person person = new Person();//person为对象的引用
System.out.println(person.age);//默认值为0
System.out.println(person.name);//默认值为null
//System.out.println(person.count);//会有警告
//正确访问方式
System.out.println(Person.count);//0
System.out.println(Person.COUNT);//99
Person.staticTest();
person.eat();
person.sleep();
}
}
3.修饰代码块
静态代码块
在类加载的时候执行且只会执行一次,可以写在类中的任何地方,最先执行。
4.修饰内部类
静态内部类
public class Test {
static class B{
}
public static void main(String[] args) {
B b1 = new Test.B();
B b2 = new B();
}
}
在当前类Test中使用时,和静态变量,静态方法类似,也可以把Test.B()省略写为B()