Member var and Static var.

5910 ワード

 1 /*

 2 member variable and static variable:

 3 1,invoke ways:

 4 member variable,also called 'instance' variable,which can only be invoked by instance.

 5 static variable,also called 'class' variable,which [can also] invoked by class,and it is recommended that it invoked using 'class' rather than 'instance'.

 6 2,storage places:

 7 instance variable is stored in the 'heap',

 8 whereas, static variable is stored in the static area of the 'method area'.

 9 3,life cycle:

10 static var exists as the existence of the class, and gone as the disappear of the class.[general] the 'class' exists when the JVM works,and disappear when the JVM stopped.

11 instance var exists as the existence of the instance,and gone when the instance was released.

12 4,memory location:

13 static var located in the static area of the Method Area,whereas,

14 instance var located in the heap.

15 */

16 package kju.obj;

17 

18 import static kju.print.Printer.*;

19 public class InstanceVarStaticVar {

20     public static void main(String[] args) {

21         println(Person.country);    //use the 'static' var by 'class' instead of the instance.

22         printHr();

23         Person lily = new Person("lily");

24         println(lily.getName());

25         println("set:");

26         lily.setName("lucy");

27         println(lily.getName());

28         println();

29     }

30 }

31 

32 class Person {

33     public static final String  country = "cn";

34     public Person(String name) {

35         this.name = name;

36     }

37 

38     public void setName(String name) {

39         this.name = name;

40     }

41     public String getName() {

42         return name;

43     }

44 

45     private String name;

46 }