non-static variable this cannot be referenced from a static context

While practicing Java today, I found an interesting question that may actually be common sense for computer science majors. But I don’t know how many friends like me, or even computer related professional friends noticed this problem.

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: