There are generally three variables in Java: Class variables, member variables, and local variables. class variables
1. Let's look at the following example for a class variable
public class demo6{public String name; public int age; public static String sex= "male"; Public Demo6 (String name, int age) { this.name = name; This.age = age;; } public void Say () { System.out.println ("My Name is" +name+ ", I Am" +age+ "year old."); public static void Main (String args[]) { Demo6 obj = new Demo6 ("Alex"); Obj.say (); System.out.println ("I Am" +sex+ "health");// System.out.println ("I Am" +age+ "year old");} }
Class variables can be accessed without instantiation (PS: If an instance changes the value of a class variable, the other instance calls the value of such a variable)
If you remove the comment
System.out.println ("I" +age+ "year");
, you will get an error: Error: (+) Java:/users/lsf/ideaprojects/javapractice/src/demo6.java:19: Cannot reference a non-static variable from a static context
2. Next look at the member variables and local variables, or look at this example, make a little change
public class demo6{public String name; public int age; public static String sex= "male"; Public Demo6 (String name1, int.) { this.name = name1; This.age = age;; } public void Say () { System.out.println ("My Name is" +name+ ", I Am" +age+ "year old.); / System.out.println ("My name is +name1+", I'm "+age+" this year); } public static void Main (String args[]) { Demo6 obj = new Demo6 ("Alex"); Obj.say (); System.out.println ("I Am" +sex+ ");} }
The result is correct when you execute the following sentence:
System.out.println ("My name is +name+", I Am "+age+" this year);
This is because name is a member variable and is valid throughout the instance. And name1 is a local variable, only valid in the method body, if you call name1 as follows, you will get an error
System.out.println ("My name is +name1+", I Am "+age+" this year);
The error message is:
Error: (+) Java: no symbols found
Symbol: Variable name1
Location: Class Demo6
Describe Java class variables, member variables, and local variables in an instance