[英]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 .
是否正确,取决于您要赋予该领域的含义 。
A
, then declaring it static
is the right approach, indeed. A
任何实例的情况下就存在,则将其声明为static
是正确的方法。 A
(an instance of A
), then it shouldn't be static
(hence, be an instance
field). A
( 实例 A
),那么它不应该是static
(因此,是一个instance
字段)。 In this case: 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.