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

时间:2015-07-17 10:53:59

标签: 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
      }
  }

4 个答案:

答案 0 :(得分:6)

您必须考虑几点:

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

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

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

  4.   

    通常静态对象用于维持状态。

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

答案 1 :(得分:2)

您获得的错误与静态/实例访问无关。由于Java语法无效,它们只是编译时错误。

您不能使用publicstatic等字段修饰符来声明方法内的局部变量(无论是静态方法还是实例方法)。

只需删除不必要的修饰符:

  public static void main(String[] args) {
      Rent r1 = new Rent();
      Rent r2;
  }

  public static Rent r3;

  public void def() {
      Rent r4 = new Rent();
      Rent r5;
  }

答案 2 :(得分:1)

首先,不允许在方法中使用访问修饰符(public,private,protected)声明变量。您也不应该在方法中将变量声明为static

您在方法之外声明的那些变量是类的成员。

有两种类型的变量:

  • 实例变量(非静态成员)
  • 类变量(静态成员)
  

我可以看到无法在方法中创建非静态类的静态对象吗?

静态意味着它属于该类。它甚至在您实例化对象之前就存在了。这就是你可以直接在类中调用静态方法的原因。

那么什么是静态成员?

  • 静态成员由同一个类的所有对象共享。
  • 甚至在您实例化(创建)对象之前就已存在。
  • 它属于该类,而不属于任何单个对象。

示例:

class Pond
{
    static double waterTemp = 17.5;  //Every Pond object shares the same value
    int numFishes;                   //Belongs to each individual Pond object
}

如何访问静态成员:

System.out.println(Pond.waterTemp); //Preferred
System.out.println(Pond.numFished); //Not allowed

//OR

Pond pond = new Pond();  
System.out.println(pond.waterTemp); //Not necessary, but allowed
System.out.println(pond.numFished); //The only way to get numFishes

答案 3 :(得分:0)

非静态方法与实例关联,因此需要在访问实例之前创建实例。但是,静态方法与类有关,因此即使没有实例也应该可以使用。这些约束导致静态方法不能在非静态方法中创建。