java错误Cannot make a static reference to the nonstatic method

转:

我在一个类中写了一个public void getDate()方法和一个main方法,在main方法中直接调用getDate()方法,于是就出现了这个错误提示。后来实例化类,再用实例化的类调用getDate()方法就没问题了

在静态方法中,不能直接访问非静态成员(包括方法和变量)。 

因为,非静态的变量是依赖于对象存在的,对象必须实例化之后,它的变量才会在内存中存在。例如一个类 Student 表示学生,它有一个变量 String address。如果这个类没有被实例化,则它的 address 变量也就不存在。而非静态方法需要访问非静态变量,所以对非静态方法的访问也是针对某一个具体的对象的方法进行的。对它的访问一般通过 objectName.methodName(args......) 的方式进行。 

而静态成员不依赖于对象存在,即使是类所属的对象不存在,也可以被访问,它对整个进程而言是全局的。因此,在静态方法内部是不可以直接访问非静态成员的。 

Static methods cannot call non-static methods. An instance of the class is required to call its methods and static methods are not accociated with an instance (they are class methods). To fix it you have a few choices depending on your exact needs.

/**
*  Will not compile
*/

public class StaticReferenceToNonStatic
{
   public static void myMethod()
   {
      // Cannot make a static reference
      // to the non-static method
      myNonStaticMethod();
   }

   public void myNonStaticMethod()
   {
   }
}

/**
* you can make your method non-static
*/

public class MyClass
{
   public void myMethod()
   {
      myNonStaticMethod();
   }

   public void myNonStaticMethod()
   {
   }
}

/**
*  you can provide an instance of the
*  class to your static method for it
*  to access methods from
*/

public class MyClass
{
   public static void myStaticMethod(MyClass o)
   {
      o.myNonStaticMethod();
   }

   public void myNonStaticMethod()
   {
   }
}

/**
*  you can make the method static
*/

public class MyClass
{
   public static void myMethod()
   {
      f();
   }

   public static void f()
   {
   }
}

 

原文地址:https://www.cnblogs.com/youxin/p/2465018.html