简体   繁体   English

在Java中声明静态对象

[英]Declaring static object in java

I have a class consisting of static methods.They need to use an object of another class. 我有一个包含静态方法的类,他们需要使用另一个类的对象。

Say

class A{
  B obj = new B();

public static void method()
{
  //using obj here
 }
}

Is declaring static B obj = new obj() the right approach here? 在这里声明static B obj = new obj()是正确的方法吗?

Is declaring static B obj = new obj() , right approach here? 在这里声明静态B obj = new obj(),对吗?

Yes, if you are using obj inside your static method. 是的,如果您在静态方法中使用obj。 And, that's the only way to access obj inside the method. 而且,这是在方法内部访问obj的唯一方法。

You can't access class A's instance fields without an object of class A 没有类A的对象,您将无法访问类A的实例字段

Just change the declaration like this and you are fine: 只需像这样更改声明,就可以了:

class A {

    private static B obj = new B();

    public static void method() {
        System.out.println(obj);
    }
}

class B {}

Yes. 是。 That is correct. 那是对的。

class A{
  static B obj = new B();

public static void method()
{
  // now you can use obj here.
 }
}

如果不将obj声明为static成员,则不能在static方法中使用它们。

Is declaring static B obj = new obj() , right approach here? 在这里声明静态B obj = new obj(),对吗?

This solves your problem, indeed (see below). 确实可以解决您的问题(请参阅下文)。 Whether or not it is the right approach depends on the meaning you want to give that field . 是否正确,取决于您要赋予该领域的含义

  • If the field has a global meaning, and it makes sense that it exists without any instance of the class A , then declaring it static is the right approach, indeed. 如果该字段具有全局含义,并且在没有类A任何实例的情况下就存在,则将其声明为static是正确的方法。
  • If the field has a meaning only for an object of class A (an instance of A ), then it shouldn't be static (hence, be an instance field). 如果该字段仅具有用于类的对象的意义A实例 A ),那么它不应该是static (因此,是一个instance字段)。 In this case: 在这种情况下:
    • either it does not make sense that your static method needs to access this field. 要么您的静态方法需要访问该字段都没有意义。
    • or it does not make sense for your method to be static because it is instance-related 否则您的方法是静态的就没有意义,因为它与实例相关

Why static solves the problem: 为什么静态解决问题:

The static keyword sort of means " what I declare here does not depend on an instance of this class, but only on the class itself ". static关键字的意思是“ 我在这里声明的内容不依赖于此类的实例,而仅依赖于类本身 ”。

This is why a static method cannot access an instance field (non-static field). 这就是为什么static方法无法访问实例字段(非静态字段)的原因。 The method can be called via A.method() but the field does not exist while no instance new A() has been created, so the method can obviously not use it. 可以通过A.method()调用该方法,但是在没有创建new A()实例new A()情况下该字段不存在,因此该方法显然不能使用它。

If the field is declared static , then it can be accessed because it is also independent from instances. 如果将该字段声明为static ,则可以访问该字段,因为它也独立于实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM