1 classCar2 {3 String color;4 intNumber ;5 6 voidRun ()7 {8System. out. println (color+"::"+Number );9 }Ten } One A classCardemo - { - Public Static voidMain (string[] agrs) the { -Car C =NewCar ();//c is a variable of class type. - //C.color = "Blue"; - //c.number = 4; + C.run (); - } + } A at /* - the relationship of a class to an object: - class: The description of a thing. Attributes and behaviors need to be reflected. - object: A sample (entity) that creates an object that invokes the properties and behavior that it has. - - the difference between a member variable and a local variable: in difference One: the location of the definition is different. - (1) The member variable is defined in the class. to (2) Local variables are defined in the method. + - Difference Two: the location in memory is different. the (1) member variables are stored in the object of the heap memory. * (2) Local variables are stored in the stack memory method. $ Panax Notoginseng Difference Three: The declaration period is different: - (1) The member variable appears as the object appears and disappears as the object disappears. the + explanation of the distinction three (1): A class Car the { + //Properties of things: - String color; $ int number; $ - //Things act: - void Run () the { - System.out.println (color+ "::" +number);Wuyi } the - /* Wu Description: When this run method runs, the call is not the one defined in the car class . - Color and number, but the color and number of objects in the in- memory heap memory. About */ $ } - classCardemo - { - Public Static voidMain (string[] agrs) A { +Car C =NewCar (); theC.color ="Red"; -C.number =4; $ C.run (); the } the } the(2local variables occur as the method runs, disappearing as the stack of methods is played. the - Difference Four: initialization differs: in(1The member variable has a default initialization value because it is in heap memory. the(2Local variables do not have default initialization values and must be initialized before they can be used. the /* About One question is: Why doesn't Java initialize local variables as well? the The reason is that once Java initializes the local variables, the local variables the It takes up space in memory. When did Java's mechanism come into use? the local variables, and when to open up space for local variables in memory. + - //If it is written as follows: When the Run method is in the stack, it will be a local variable in memory the //x opens up space. Bayi void Show () the { the int x = 4; - } - the //If written as follows: When the Run method is in the stack, it is not in memory as a local variable the //x opens up space. the void Show () the { - int x; the } the */ the 94*/
The difference between local variables and member variables in Java