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:
- Failed to import static file of vue3 static resource. There is no static folder
- Nuxt cannot find the static resource in static
- Global variable error: unboundlocalerror: local variable ‘l’ referenced before assignment
- error: invalid use of non-static member function
- C ා programming encountered an object reference is required for the non-static field, method, or property error
- [Qt] error: call to non-static member function without an object argument
- Python UnboundLocalError: local variable ‘num’ referenced before assignment
- Python error: local variable ‘XXXX’ referenced before assignment
- Solving Python error: local variable ‘a’ referenced before assignment
- [How to Solve]Warning: connect.static is not a function
- Spring MVC – enable static resource access
- Request cannot get static resource
- node.js Static resource acquisition failed
- Scala Flink Watermarker Error: Static Methods in interface require -target:jvm-1.8
- SSM project controller layer calls static method to report an error
- The SSM project cannot load various static resources
- NDK Version Clang++: error: unknown argument: ‘-static-openmp‘
- VirtualBox + CentOS 7 virtual machine setting static IP address of host only NIC
- ImportError: dlopen: cannot load any more object with static TLS
- Spock + powermock simulation static method reports an error java.lang.classcastexception