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.