20180228 java static修饰符
static修饰的资源不属于任何一个对象,而是属于类本身。
static修饰符表示静态的,可修饰字段、方法、内部类,其修饰的成员属于类,也就是说static修饰的资源属于类级别,而不是对象级别。
static修饰符的特点:
1、static修饰的成员(字段/方法,随之所在类的加载而加载)。
当jvm把字节码加载时,static修饰的成员就在内存中生成了。
2、static修饰的成员优先于对象的存在,对象是通过手动 new关键字创建出来的。
3、static修饰的成员被该类型的所有对象共享。
根据该类创建出来的对象都可以访问static修饰的成员。
4、直接使用类名访问static成员。
因为static修饰的成员直接属于类,不属于对象,所以可以直接使用类名访问static成员。
eg:
class Person
{
string name;
int age;
int totalNum = 5;//人的总人数
Person(string n,int a)
{
name = n;
age = a;
tatalNum++;
}
void die()
{
totalNum--;
System.out.println("去世。。。");
}
//只有人类才会毁灭
static void destory()
{
totalNum = 0;
System.out.println("毁灭。。。");
}
}
class PersonDemo
{
public static void main(String[] args)
{
System.out.println(Person.totalNum);//此时输出 5
Person p1 = new Person("will",15);
System.out.println(Person.totalNum);//此时输出 6
Person p2 = new Person("lucy",15);
System.out.println(p1.totalNum)//使用对象访问static成员,
//表面上使用对象去访问
//static成员,其本质是使用
//类名访问,和对象没有任何关系, 输出7
System.out.println(Person.totalNum);//使用类名访问static成员,输出 7
p2.die();
System.out.println(Person.totalNum);//此时输出 6
Person.destory();//此时 totalNum = 0
}
}