Today, when I hit the code, I encountered this problem, the general problem can be simplified as such;
public class Test1 {public
String get ()
{return
"123";
}
public static void Main (string[] args)
{
string string =get ();
}
}
Show
Cannot make a static reference to the Non-static method get () from the type Test1
Well, I decided to change it.
public class Test1 {public
String get ()
{return
"123";
}
public static void Main (string[] args)
{
static string string =get ();
}
}
But it's still wrong ....
I flipped the Java book to know
Static methods in 1.java cannot call non-static methods and members directly, nor can you use the This keyword (this is the cause of this problem, I called the non-static get method with the static Main method).
Reason explanation: A static method or attribute in a class, in essence, it is not a member of this class, when the Java Virtual machine installed in the class, these static things already have objects, it is only in this class "aliens", do not need to pass the class constructor (constructor) class implementation of the instantiation; A Non-static property or method that does not exist in the load of a class and relies on the constructor of the class to be dependent on the instance object of the class. So when a non-static method is invoked in a static method , the compiler complains (cannot make a is static reference to the Non-static methods Func () from the Type a). In Java, a local variable in a method body cannot be declared as a static main () function, not a return value, and a formal parameter is an array. Static members can be arbitrarily invoked by Non-static members
Originally static so anti-human, that want this to do?
Presumably to make multiple classes share a single data.
I've probably modified it to make the function static, declaring the variable as global static
Method One:
public class Test1 {
static string string;
public static String get ()
{return
"123";
}
public static void Main (string[] args)
{
String =get ();
System.out.print (string);
}
}
Method Two
public class Test1 {public String get () {return "123";
public static void Main (string[] args) {Test1 c = new Test1 ();
String string = C.get ();
System.out.print (string); }
}