Java cannot reference non-static methods from static context

The First

This problem appears in the method of the class.
The simplest solution is to add static before the error method:
chestnut: public void Function()——>public static void Function()
(complete test code attached)

A deeper understanding is as follows. The
first thing to know is: A static method can be used when no instance is created, and a member variable declared as non-static is an object property, which is only referenced when the object exists, so if no instance is created in the object When we call a non-static member method in a static method, it is naturally illegal, so an error will be reported.

For example,
there are two classes: Main class and Function class. Functionl has public void fun1(); public static void fun2();.
Insert picture description here
Insert picture description here
Generally speaking, to use the methods in the Function class, the first thing that comes to mind is to create an instance first. Function fun = new Function();
fun.fun1(); the
Insert picture description here
result is shown in the figure . As
Insert picture description here
long as it is called through the instance fun, there is no need to add static to public void fun1().

In addition to the above operations that can call methods, there is another operation: call methods without creating an instance. Function.fun2(); The Insert picture description here
result is shown in the figure.
However, calling public void fun2(); failed.
Insert picture description here
So public void fun2(); it is necessary to modify it to public static void fun2(); the
result is shown in the figure.
Insert picture description here
Post a complete code

Main

public class Main
{	
	public static void main(String[] args)
	{
		Function fun= new Function();
		fun.fun1();
		Function.fun2();
	}
}

Function

public class Function
{	
	public void fun1()
	{
		System.out.println("1.通过实例调用方法。");
	}
	public static void fun2()
	{
		System.out.println("2.不创建实例直接调用放方法。");
	}
}

The compiler I use is JCreator, and I created a Main.java and Function.java to execute it. If I put the Function class in Main, it will report an error. I don’t know what’s going on. I’ll check it another day.

Guess you like

Origin blog.csdn.net/qq_43228135/article/details/83106716