Java study notes objects (three) for --- Static keyword

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

  1. 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

  2. Precedence over object exists
    (static is to exist, the object is the existence of)

  3. It is shared by all objects

  4. 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

  1. 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.
  2. Static methods can only access static members.
    Non-static method can access both static can also access non-static.
  3. A static method can not define this, super keyword. Because static precedence over the object exists.

Static pros and cons

Lee:

  1. Shared data object spatially separate storage, saving space.
  2. You can directly use the class name to call, easy call.

Disadvantages:

  1. Life cycle is too long.
  2. Greater access limitations.

Guess you like

Origin www.cnblogs.com/liyuxin2/p/12297521.html