gogoWebsite

"Only static variables and static methods can be called in static methods" detailed explanation

Updated to 2 days ago

Static methods and static variables can be called, and non-static methods and non-static variables can also be called.

public class Test {

 public Test() {};
 public Test(int i) { = i;}

 public static int m = 5;
 public int n = 10;

 public void fun1() {("non-static method fun1");}
 public static void fun2() {("static method fun2");}

 //Test what does "only static variables and static methods can be called in static methods" mean
 public static void main(String[] args) {
  //Calling static methods will not report an error
  //fun2();

  //Calling static variables will not report an error
  (m);

  //Unable to reference non-static method fun1() from static context
  //fun1();

  //Unable to reference non-static variable n from static context
  //(n);

  //You can call the constructor of a non-static method in a new object in a static method. Regardless of whether the constructor is default or not, the following code can be executed correctly.  Therefore, it is believed that: "In the compilation stage, the compiler will not check the specific objects and related operations involved in the static method."  In this way, a solution is also provided to access non-static methods and non-static properties in static methods.
  //Test t = new Test(8);
  //t.fun2();
  //t.fun1();
  //();
  //();
 
 }
 }