Bhupathy A P
Bhupathy A P

Reputation: 444

what happens while Creating object for class with main method in java

Whats happens when i create object for class with main method.Can i able to use those instance variables within main method,since they are in same class?

   class matrix
 {

int i,j;   
int a[10];
  Scanner one=new Scanner(System.in);
  public static void main(String args[])
   {
   matrix obj=new matrix();
   System.out.println("Enter the numbers");
   obj.create(a); // is it correct to use 'a'(instance variable) inside main() ?     
   }



   void create(int[] a)
   {
    // code
 }

Upvotes: 0

Views: 1201

Answers (3)

Code Geek
Code Geek

Reputation: 485

You cannot use obj.create(a) because it is not static, meaning it has to be referred by an instance variable.

So you would have to use

obj.create(obj.a)

Upvotes: 0

sol4me
sol4me

Reputation: 15698

No, because you cannot use non-static variable in static method, change

obj.create(a)

to

obj.create(obj.a)

Upvotes: 3

Suresh Atta
Suresh Atta

Reputation: 121998

You cannot use instance variables inside main method since they are not static. You can use only static members. However you can use the members of newly created instance inside static context.

i.e obj.create(a.anyMemberofObjecta);

Read more about static context in Java.

Upvotes: 1

Related Questions