content
Static: Static
usage
Static is a modifier for modifying member (member variables, member functions), when the members are static modification, in addition to the callee, but also the class name can be called directly.
For example
class Person {
String name; //成员变量,实例变量
static String country = "CN"; //静态的成员变量,类变量
}
public class StaticDemo {
public static void main(String[] args) {
Person p = new Person();
System.out.println(p.country); //使用对象调用
System.out.println(Person.country);//直接使用类名调用
}
}
operation result:
CN
CN
Feature
Static keyword modified by members of the class with the load and load (with the disappearance of class disappear), that rely on static variables do not need to create an object exists in memory, so it's the longest life cycle
Precedence over object exists
(static is to exist, the object is the existence of)It is shared by all objects
It can be directly invoked by class name
The difference between the instance variables and class variables
Storage location
Class variables as present in the class loading zone method.
With the establishment of an object instance variables exist in the heap memory.
Life cycle
Class variables longest life cycle, with the disappearance of class disappear.
The establishment of the life cycle of an instance variable depends on the object and disappear.
Static Precautions
- For data, we need to distinguish between specific data and shared data.
With the object-specific data storage, it does not use static modification. Due to the long life cycle of a static variable, if you define too many static variables can lead to excessive memory is consumed. - Static methods can only access static members.
Non-static method can access both static can also access non-static. - A static method can not define this, super keyword. Because static precedence over the object exists.
Static pros and cons
Lee:
- Shared data object spatially separate storage, saving space.
- You can directly use the class name to call, easy call.
Disadvantages:
- Life cycle is too long.
- Greater access limitations.