problem with object in java

What about the objects which we define outside static method ? how to use them ?
Example:=> In the following code how to use object “obj1”. I know “obj1” can’t be used in static method. But it can be used in non-static method. So, How to use “obj1” in method “nonstatic” ?

Code:=>

class Test {   
    int a,b;  
    String name;  
    Test obj1=new Test();
    public void nonstatic(){}
    public static void main(String[] args){  
        System.out.println("How to use obj1");
    }
}

Why are you asking same question again? You cannot use instance variables in static method (where you have no instance)…

That’s what compiler is trying to tell you when you do something like

 obj.a

in main()

Cannot make a static reference to the non-static field obj1

2 Likes

Initialize the using the static keyword before the type. When you initialize objects or primitive variables as global variables you have to add the keyword static if you want to use them in static methods, otherwise you will only be able to use them in non-static methods. Note that you can still use static variables in non-static methods, it just doesn’t work the other way around. Are you picking up Java now or did you just start programming? Either way you should check this link to understand the basics, even if you just switched languages, it doesn’t hurt to spare some time reviewing these things.

1 Like

i should say make on object of class Test and then try to access obj1…might work

Can I use object “obj1” in non-static method ?
If yes, How ?

In the above code How can I use Object “obj1” in non-static method ??

I answered it here - http://discuss.codechef.com/questions/37959/a-doubt-in-java You have to create instance and then you can use non-static methods on that instance…

Nice link I have to check it too :wink:

1 Like

@ayush1993, check @betlista’s answer… Are you a novice in programming or just in Java? Having that information might be useful for us to provide better answers and guide you in the right direction…

@bradley, Now you got my my question.I tried it but got error.

@junior94, you still not got my question. See I have modified my question and then try to answer it.