Idle talk less, get down to business, look at the code first.
Error code 1:
class ConsDemo {
private static String name; //declare name attribute
private static int age; // delcare age attribute
public static void tell(){
System.out.println("name: "+this.name+",age: "+this.age);
}
}
The above code will report an error, such as the question.
Why?
First, adjust the code as follows:
class ConsDemo {
private String name; //declare name attribute
private int age; // delcare age attribute
public void tell(){
System.out.println("name: "+this.name+",age: "+this.age);
}
}
The above code can be run or rewritten as follows:
Fixed code 2:
class ConsDemo {
private static String name; //declare name attribute
private static int age; // delcare age attribute
public static void tell(){
System.out.println("name: "+name+",age: "+age);
}
}
So here’s the conclusion:
If this pointer is removed from the error code 1, the error will become: non-static variable name cannot be referenced from a static context; The static variable name,age, cannot be found in the context.
So the tell method static declaration is removed from code one, while the name is removed from code two, and the static declaration keyword is added to the age property.
Therefore, the following conclusions can be drawn:
You can only use static variables in static methods;
The same:
Class methods can only use class variables.
Read More:
- @Value sets the default value
- The difference between sleep() and wait() in Java
- Macro generated_ UCLASS_ Body () and generated_ Analysis of body ()
- Error: global variable is ambiguous (conflict between using namespace STD and global variable)
- Java gets the type t.class of generic t
- Three ways to get form data in struct2
- Syntax error, insert “VariableDeclarators” to complete LocalVariableDeclaration
- Conversion between list and string array
- Java uses the same event listener for the same type of component
- Java – read all the files and folders in a certain directory and three methods to get the file name from the file path
- The method of Java jumping out of loop
- Java.lang.Character . isdigit() and isletter() methods
- Solution of idea using @ Autowired annotation to report errors
- Android:Field can be converted to a local varible.
- Java – how to shuffle an ArrayList
- [Two Sigma OA] Longest Chain
- JAVA lambda Syntax error on tokens, Expression expected instead
- Encapsulation of adding, deleting and modifying database by JDBC
- [Qt] error: call to non-static member function without an object argument
- Java compareto() method