Reputation: 315
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
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.
A
, then declaring it static
is the right approach, indeed.A
(an instance of A
), then it shouldn't be static
(hence, be an instance
field). 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".
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
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
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
Reputation: 580
If you don't declare obj
as a static
member, you can't use them in static
methods...
Upvotes: 1
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