Reputation: 444
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
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
Reputation: 15698
No, because you cannot use non-static variable in static method, change
obj.create(a)
to
obj.create(obj.a)
Upvotes: 3
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