为什么不能在方法内创建非静态类的静态对象?

use*_*411 1 java static

我可以看到非静态类的静态对象不能在方法内创建?

码:

  public class Rent {

      public void abc() {
          System.out.println("Non static method");
      }
      public static void def() {
          System.out.println("this is static method");
      }
  }

  public class SampleJava {

      public static void main(String[] args) {
          Rent r1 = new Rent();
          public static Rent r2; //not allowed in static method
      }

      public static Rent r3; //allowed outside method

      public void def() {
          Rent r4 = new Rent();
          public static Rent r5; //not allowed in non-static method either
      }
  }
Run Code Online (Sandbox Code Playgroud)

Nak*_*l91 6

你必须考虑几点:

  1. 静态数据类似于静态方法.它与实例无关.声明为static的值没有关联的实例.它存在于每个实例中,并且仅在内存中的单个位置声明.如果它被更改,它将针对该类的每个实例进行更改.

  2. 您使用的访问修饰符仅允许用于类级别而不是方法级别.在你的例子中:

    public static void main(String[] args) {
      Rent r1 = new Rent();
      public static Rent r2; //Will give compile time error.
    }  
    
    Run Code Online (Sandbox Code Playgroud)
  3. 考虑到" 静态 " 的目的,如果要在方法中声明静态对象,则其范围将仅绑定到该特定方法.

通常,静态对象用于维持状态.

例如,您的数据库连接逻辑可能具有单例类,并且此类的对象应保持您的数据库连接状态.这些对象必须是并且必须处于类级别.