user3505394
user3505394

Reputation: 315

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?

Upvotes: 1

Views: 289

Answers (5)

Joffrey
Joffrey

Reputation: 37829

Is declaring static B obj = new obj() , right approach here?

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.
  • 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). 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".

This is why a static method cannot access an instance field (non-static field). 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.

If the field is declared static, then it can be accessed because it is also independent from instances.

Upvotes: 0

Harmlezz
Harmlezz

Reputation: 8078

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 {}

Upvotes: 2

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35587

Yes. That is correct.

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

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

Upvotes: 1

deb_rider
deb_rider

Reputation: 580

If you don't declare obj as a static member, you can't use them in static methods...

Upvotes: 1

Abimaran Kugathasan
Abimaran Kugathasan

Reputation: 32488

Is declaring static B obj = new obj() , right approach here?

Yes, if you are using obj inside your static method. And, that's the only way to access obj inside the method.

You can't access class A's instance fields without an object of class A

Upvotes: 2

Related Questions