Java中的static关键字
Java中的static
- static 关键字
- 用于修饰成员变量和成员函数
生命周期
- static (类) 变量生命周期最长,随着类的消失而消失。
- 非 static (实例) 变量随着对象的消失而消失。
内存位置
- static成员变量位于静态域。
- 非static 成员变量位于系统在堆上为每个对象分配的区域。
- static 特点
- 随着类的加载而加载
- 优先于所有的对象存在
- 被所有对象所共享
- 可以直接被类名所调用
使用注意
- 静态方法只能访问静态成员
- 静态方法中不可以写this,super关键字
- 主函数(main)是静态的
- 使用时,可以使用Object.staticFunction(staticNumber)或者Class.staticFunction(staticNUmber)
example
class Person
{
public Srting name;
public static void country="CN";
public void show()
{
System.out.println("name="+name+":::::country="+country)
}
}
class PersonDemo
{
public static void main(String[] args)
{
System.out.println(Person.country);//1. Class.staticNumber
Person p=new Person();
System.out.println(p.country);//1. Object.staticNumber
}
}
下面说一下Cpp中的static
- 关于初始化,cpp中的static变量初始化要在类的外部,所以代码应该是这个样子的。
- 在访问形式上,cpp中书写为 Person::country,java中则与非静态变量一致,采用Person.country.
class Person
{
public:
string name;
static string country;
};
Person::country="CN";//这句通常写在cpp文件当中