Learning Java for a long time, for the basic knowledge of Java although usually know how to use, but people suddenly asked you who and who is what relationship, or a little rusty. Now that we've talked about this, I'll rearrange the idea of the relationship between instance variables, local variables, class variables and final variables in Java today. As the saying goes, "good memory is better than bad writing", here to share.
Let's start with local variables: This is the first thing we touch in Java or other programming languages, defined in a method that must be initialized before it is used, and the lifecycle is valid in this method.
Instance variable: It is only available after instantiating the object, and the variable is owned by the object. Whenever an object is instantiated, a copy is always created and initialized, and if no explicit initialization is performed, a default value is initialized. The replicas of each instantiated object are independent of each other, and there is no coupling between them.
Class variable: The variable is decorated with the static modifier and can be used (class name. Variable name) as the class is loaded, belonging to the class. Load only once in a program, allocating separate storage space (static area), and all instantiated objects share class variables.
Final variable: Use the static final modifier to indicate that the variable is a constant that cannot be modified after initialization, similar to a global variable in C + +, although not in Java.
Examples are as follows:
public class Variabletest
{
char ch = ' a ';
public static int numint = 100; # member variable public
STAITC int teststatic ()
{
static final int i = 2; # static final variable
int x = 5; #局部变量
System.out.println (i+x);
public static void Main (string[] args)
{
System.out.println (variable.numint);
Variabletest test = new Variabletest ();
Test.teststatic ();
System.out.println (test.ch);
}
Run Result: 100
7
A