-4
class A
{
int i = 10;
public static void main(String[] args)
{
A a= new A();
a.i=20;
}
}

is running fine but when try to write following code

class A
{
A a= new A();
int i = 10;
public static void main(String[] args)
{
a.i=20;
}
}

it is giving compile time error. It means that whatever(assume reference variable) we write inside the static method is treated as a static variable implicitly.

  • Instances are pretty much the opposite of static. Background info on your problem: http://stackoverflow.com/questions/2559527/non-static-variable-cannot-be-referenced-from-a-static-context – Jeroen Vannevel Jan 17 '15 at 15:10
  • why is it mandatory to create instance inside the static method? – Raju Kapadne Jan 17 '15 at 15:19

1 Answers1

0

You are mixing up class scope, method scope, and instance scope.

First remember that when you have something that is static, it is available to all instances of that class. When something isn't static, it is only available to a specific instance of a class, and is not shared. Because of that, static methods cannot act on instance variables (or methods).

In the first example, you create an A scoped to the main() method. The fact that main() is static has nothing to do with it, this is method-level scoping. When you call .i on that instance of A, you are calling it on the instance local to your scope.

In the second example, you are saying that whenever an A is instantiated, it will have another instance of A within it (which leads to other problems, see below). This is at the object instance scope. When you try to call it from your static-scoped main() method, the compiler has no idea which specific instance of A you want to use. Each one has its own version of i.

And finally, by creating an instance of A within every other instance of A (A a = new A();) your code will never run, you'll get a StackOverflowException.

Edit to answer question:

OK, when you do something like this:

public class Person {
    String name = null;
}

You are saying, that for every Person we create (via new), they have a name that is for them, and them only. They don't share it with anybody.

So when you do something like this:

public class A {
    A a = new A();
}

You are saying that for every A we create (via new) it has another A that is for that instance and that instance only. See where this is going? You end up infiniately creating A objects until java runs out of room on the stack for them. The first A is created, and tries to create its internal A, which tries to create its internal A and so on and so on.

Todd
  • 30,472
  • 11
  • 81
  • 89